I am trying to download image and decode it to bitmap using BitmapFactory, but decodeStream always return null. I've googled many similar questions, tried many examples, but didn't find solution.
Here is my code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void downloadButton(View v)
{
String imageUrl = "http://www.picgifs.com/bird-graphics/bird-graphics/elf-owl/bird-graphics-elf-owl-527150.bmp";
new Thread(new ImageDownloader(imageUrl)).start();
}
public void showImageButton(View v)
{
Bitmap image = ImageHandler.getImage();
if (image == null)
Log.e("Error", "No image available");
else {
ImageView imageView = (ImageView)findViewById(R.id.ImageView);
imageView.setImageBitmap(image);
}
}
}
class ImageHandler
{
static protected List<Bitmap> imagesList;
static public void addImage(Bitmap image)
{
imagesList.add(image);
}
static public Bitmap getImage()
{
if (!imagesList.isEmpty())
return imagesList.get(0);
else
return null;
}
}
class ImageDownloader implements Runnable
{
public Bitmap bmpImage;
private String urlString;
public ImageDownloader(String urlString)
{
this.urlString = urlString;
}
public void run()
{
try
{
AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
HttpGet getRequest = new HttpGet(urlString);
HttpResponse response = client.execute(getRequest);
HttpEntity entity = response.getEntity();
InputStream inputStream = null;
inputStream = (new BufferedHttpEntity(entity)).getContent();
bmpImage = BitmapFactory.decodeStream(inputStream);
//bmpImage = BitmapFactory.decodeStream(new URL(urlString).openConnection().getInputStream());
}
catch (Exception e)
{
Log.e("ImageDownloadError", e.toString());
return;
}
if (bmpImage != null)
{
ImageHandler.addImage(bmpImage);
Log.i("Info", "Image download successfully");
}
else
Log.e("Error", "Bitmap is null");
}
}
p.s showImageButton throws IllegalStateException, but I was already sick of it.
I think the problem is that once you've used an InputStream from a HttpUrlConnection, you can't rewind and use the same InputStream again. Therefore you have to create a new InputStream for the actual sampling of the image. Otherwise we have to abort the http request.
Only once we can use inputstream for httprequest, if you are trying to download another image,then it will throw an error as "InputStream already created" like this. so we need to abort the httprequest once downloaded using httpRequest.abort();
Use this:
HttpGet httpRequest = new HttpGet(URI.create(path) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmp = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();
as per my view two Reasons are there
class ImageHandler is not able to get the image
android is giving problem to take gif image from source.
I am uploading a working code hope this will solve Your Problem.
MainActivity
public class MainActivity extends Activity {
private ProgressDialog progressDialog;
private ImageView imageView;
private String url = "http://www.9ori.com/store/media/images/8ab579a656.jpg";
private Bitmap bitmap = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
Button start = (Button) findViewById(R.id.button1);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
progressDialog = ProgressDialog.show(MainActivity.this,
"", "Loading..");
new Thread() {
public void run() {
bitmap = downloadBitmap(url);
messageHandler.sendEmptyMessage(0);
}
}.start();
}
});
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
imageView.setImageBitmap(bitmap);
progressDialog.dismiss();
}
};
private Bitmap downloadBitmap(String url) {
// Initialize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = null;
try {
// getting contents from the stream
is = entity.getContent();
// decoding stream data back into image Bitmap
final Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
} finally {
if (is != null) {
is.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
getRequest.abort();
Log.e(getString(R.string.app_name), "Error "+ e.toString());
}
return null;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:text="Download Image" />
<ImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerInside"
android:src="#drawable/ic_launcher" />
</LinearLayout>
and also don't forget to give INTERNET Permission in Manifest.xml file
Related
I am a newer android developer , and i try to make an app which depend on MySQL.
so i have MySQL database and I have A php that return its data in Json format at this link here.
so i make a simple app that take this data and show it in list view by AsyncTask & Service Handler .
Note 1: I try this app with another database [Not Free Domain/website] and it work But with my database didn't work [free hosting]
Note 2: I try to comment the "Try & Catch" code at doInBackground method at AsyncTask class & make a dummy data manually So the app works !!, so what???!!
Update: i used the emulator and i got some red massages that i do not understand what its mean so i take it as screen shot
My php code:
<?php
$dbname = 'zoubg_18363398_center';
$dbserver = 'sql104.kariya-host.com';
$dbusername = 'zoubg_18363398';
$dbpassword = '28721235';
$dbconnect = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);
$getpostssql = "SELECT * FROM users";
$posts = $dbconnect->query($getpostssql);
$postsarray = array();
while($row = mysqli_fetch_array($posts, MYSQL_ASSOC)){
$temp['id'] = $row['id'];
$temp['name'] = $row['name'];
$temp['password'] = $row['password'];
$temp['email'] = $row['email'];
$temp['adress'] = $row['adress'];
array_push($postsarray, $temp);
}
echo json_encode(array("posts"=>$postsarray), JSON_UNESCAPED_UNICODE);
</blink>
My java code
public class MoveActivity extends AppCompatActivity {
ListView LVMove;
MoveAdapter moveAdapter;
ArrayList<MoveInfo> MoveList = new ArrayList<>();
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_move);
LVMove = (ListView) findViewById(R.id.lv_test);
// dummy data manually
/*
MoveInfo Move1 = new MoveInfo();
Move1.setId(1);
Move1.setSName("Ahmed");
Move1.setSPass("123456");
Move1.setSEmail("Ahmed#asdf.com");
Move1.setSAddress("CairoEgypt");
MoveList.add(Move1);
MoveInfo Move2 = new MoveInfo();
Move2.setId(2);
Move2.setSName("Ali");
Move2.setSPass("456789");
Move2.setSEmail("Ali#asdf.com");
Move2.setSAddress("AlexEgypt");
*/
new GetMoves().execute("http://centertest.kariya-host.com/testjjjsn.php");
}
class GetMoves extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MoveActivity.this);
pDialog.setMessage(" Please wait ... ");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... strings) {
String url = strings[0];
ServiceHandler serviceHandler = new ServiceHandler();
JSONObject jsonObject = serviceHandler.makeServiceCall(url, ServiceHandler.GET);
try {
JSONArray DATA = jsonObject.getJSONArray("posts");
for (int i = 0; i < DATA.length(); i++) {
JSONObject item = DATA.getJSONObject(i);
MoveInfo Move = new MoveInfo();
int id = item.getInt("id");
String name = item.getString("name");
String password = item.getString("password");
String email = item.getString("email");
String adress = item.getString("adress");
Move.setId(id);
Move.setSName(name);
Move.setSPass(password);
Move.setSEmail(email);
Move.setSAddress(adress);
MoveList.add(Move);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(pDialog.isShowing()){
pDialog.dismiss();
moveAdapter = new MoveAdapter(MoveList, getApplicationContext());
LVMove.setAdapter(moveAdapter);
}
}
}
}
ServiceHandler Code
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public JSONObject makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public JSONObject makeServiceCall(String url, int method,
List<NameValuePair> params) {
JSONObject jsonObject=null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
jsonObject=new JSONObject(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}
MoveAdapter code
public class MoveAdapter extends BaseAdapter {
ArrayList<MoveInfo> MoveList;
Context context;
LayoutInflater inflater ;
public MoveAdapter (ArrayList<MoveInfo> MoveList, Context context){
this.MoveList = MoveList;
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return MoveList.size();
}
#Override
public Object getItem(int i) {
return MoveList.get(i);
}
#Override
public long getItemId(int i) {
return MoveList.get(i).getId();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.item_list, null);
}
TextView TvIds = (TextView) view.findViewById(R.id.tv_Ids);
TextView TvNames = (TextView) view.findViewById(R.id.tv_Names);
TextView TvPasss = (TextView) view.findViewById(R.id.tv_Passs);
TextView TvEmails = (TextView) view.findViewById(R.id.tv_emails);
TextView TvAddresss = (TextView) view.findViewById(R.id.tv_addresss);
TvIds.setText(MoveList.get(i).getId()+"");
TvNames.setText(MoveList.get(i).getSName());
TvPasss.setText(MoveList.get(i).getSPass());
TvEmails.setText(MoveList.get(i).getSEmail());
TvAddresss.setText(MoveList.get(i).getSAddress());
return view;
}
}
update: every thing was right, problem was in hosting server when i change hosting server , every thing work probably Thanks for interresting
I store app-scoped-ids in my database, hoping to fetch profile pictures from them via the graph API.
This code:
String url = "https://graph.facebook.com/" + mate.getFacebookId() + "/picture?type=large";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = null;
HttpEntity entity = null;
try {
response = httpClient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
if (response != null) {
entity = response.getEntity();
}
byte[] data = null;
try {
data = EntityUtils.toByteArray(entity);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = null;
if (data != null) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
return bitmap;
...does not work and returns a white question mark, why?
The url 'https://graph.facebook.com/800397776713349/picture?type=normal' works just fine in chrome.
The semicolon on this line is missing:
String url = "https://graph.facebook.com/" + mate.getFacebookId() + "/picture?type=large"
It looks like you're using an invalid Facebook ID. Check that mate.getFacebookId() is returning a valid ID. When I use a valid ID, I'm able to return the image successfully inside an AsyncTask:
Use inside Main thread (onCreate, onActivityCreated, etc.):
GetImage retrieve = new GetImage((ImageView)findViewById(R.id.yourimageview));
retrieve.execute();
GetImage:
class GetImage extends AsyncTask<String, Void, Bitmap>
{
private ImageView view;
public GetImage(ImageView view)
{
this.view = view;
}
#Override
protected Bitmap doInBackground(String... params)
{
//Your exact code goes here
}
#Override
protected void onPostExecute(Bitmap b)
{
view.setImageBitmap(b);
}
}
First code:
`db_img = Jasonobject.getString("image");
imagelink.setText(db_img);`
The code above is grab the data from mysql database.
"imagelink" is textview.
The code will display the data into textview
"image"from mysql is string because is url link.
Second code:
new DownloadImageTask((ImageView) findViewById(R.id.qrimg)).
execute("http://localhost/project/image/pic1.jpg");
The second code is load the image base on the URL
My problem is how to pass the value from first code into .execute("HERE")
Code:
`
EditText etacode;
EditText txtName;
Button btnscanitem;
//testing
TextView imagelink;
//hidden textview
TextView texttime;
TextView textunit;
TextView textrm;
TextView textexp;
Button btnconfrim;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acode);
btnscanitem = (Button) findViewById(R.id.btnscanitem);
etacode = (EditText) findViewById(R.id.etacode);
etacode.setVisibility(View.GONE);
//testing
imagelink = (TextView) findViewById(R.id.imagelink);
btnconfrim = (Button) findViewById(R.id.btnconfrim);
btnconfrim.setVisibility(View.GONE);
img = (ImageView) findViewById(R.id.img);
img.setVisibility(View.GONE);
img.setImageResource(0);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(AcodeActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://Localhost/getproduct.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// Fetch data from Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String apromoid = Jasonobject.getString("aid");
String db_img="";
if(etcode.getText().toString().equalsIgnoreCase(apromoid)) {
db_img = Jasonobject.getString("image");
imagelink.setText(db_img);
String temp;
temp = db_img;
//String imagelink = temp;
//(db_img);
break;
}
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.acodescanner, menu);
return true;
}
public void onClick (View view){
if(view.getId() == R.id.btnscanitem){
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
String acode;
acode = scanResult.getContents();
EditText etacode = (EditText) findViewById(R.id.etacode);
etacode.setText(acode);
new task().execute();
//String textlink = getimagelink;
new DownloadImageTask((ImageView) findViewById(R.id.qrimg))
.execute(db_img);
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
`
Please have read so many on this,(it says i should not put the dialog in the doInbackground) But have been trying to get this done for a while,Its actually my first android app(with java). Please how do i show the loading bar,disable button (till there's response) and redirect to another activity on success.
public class Index extends Activity implements OnClickListener {
EditText username, password;
Button login;
String uname,pass;
TextView login_err;
HttpClient httpclient;
HttpPost htpost;
ArrayList <NameValuePair> namearray;
HttpResponse response;
HttpEntity entity;
int Server_response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
login_err= (TextView) findViewById(R.id.login_err);
initialise();
}
private void initialise() {
username = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login= (Button) findViewById(R.id.login_btn);
login.setOnClickListener(this);;
}
public void onClick(View v) {
String umail=username.getText().toString();
String pass= password.getText().toString();
if(umail.length()!=0 && pass.length()!=0){
new MyAsyncTask().execute();
}else{
Toast.makeText(getBaseContext(), "Please provide username and password",Toast.LENGTH_SHORT).show();
}
}//END onClick()
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//END convertStreamToString()
private class MyAsyncTask extends AsyncTask <Void, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Void result) {
if(Server_response==1){
mProgressDialog.dismiss();
}
}
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(Index.this, "Loading...", "Logging In...");
}
protected Void doInBackground(Void... params) {
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
htpost = new HttpPost("http://10.0.2.2/fanaticmobile/log_in.php");
//Assign input text to strings
uname= username.getText().toString();
pass= password.getText().toString();
//Next block of code needs to be surrounded by try/catch block for it to work
try {
//Create new Array List
namearray = new ArrayList<NameValuePair>();
//place them in an array list
namearray.add(new BasicNameValuePair("username", uname));
namearray.add(new BasicNameValuePair("password", pass));
//Add array list to http post
htpost.setEntity(new UrlEncodedFormEntity(namearray));
//assign executed form container to response
response= httpclient.execute(htpost); //response from the PHP file
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode()==200){
//assign response entity to http entity
entity= response.getEntity();
//check if entity is not null
if(entity != null){
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON Object. assign converted data as parameter.
JSONObject jresponse = new JSONObject(convertStreamToString(instream));
//assign json responses to local strings
String logged= jresponse.getString("logged");
if(logged.equals("true")){
Server_response=1;
//Please i want to redirect to a new activity here
}else{
Log.d("Error Invalid credentials",logged);
Server_response=0;
}
}
}
} catch(Exception e){
Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
return null;
}
return null;
}
}
}
You should take a look at the loginActivity class from the android sdk there's a template that do what you want.
They have a method that shows an animation while the asynctask is running, you just have to call it before executing your asynctask like that
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute();
here's the method:
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
and then in your asynctask you use onPostExecute which will be called after the asynctask is completed and you can stop the login animation and launch a new activity from there
protected void onPostExecute(String[] userDetails) {
showProgress(false);
}
I'm a beginner with android programming.
I'm having some problem with downloading a file with android
I used Httpost, Httpget and hhtpurlconnection
the two first aren't working at all
and the the third can't download tow times
I want a way to download different xmls to string or inputstream (or something convertable to them) to parse those XMLs.
besides the method should be able to do something like this :
conn.setRequestProperty("Authorization", "Basic " + encodedStr);
because the xmls are responses from an API
Here I am putting an example how to download an image file from server. I am asuming that on your local server there is a picture folder and you are downloading pic from that..
Use following code it may help you..
public class DownloadType1 extends Activity{
String dwnload_file_path = "http://10.0.2.2/pictures/webicon.PNG";
String dest_file_path = Environment.getRootDirectory()+"/pictures/img1.png";
ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.download1);
}
public void onClick(View v) {
dialog = ProgressDialog.show(DownloadType1.this, "", "Downloading file...", true);
new Thread(new Runnable() {
public void run() {
downloadFile(dwnload_file_path, dest_file_path);
}
}).start();
}
public void downloadFile(String url, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
}
Below an example that you can use to download a file. Naturally you will have to use a correct URL.
public InputStream downloadXmlFileStreamUsingUrl(final String url) {
log.info(String.format("downloadXmlFileStreamUsingUrl: %s", url));
final HttpGet getRequest = new HttpGet(url);
HttpClient client;
try {
client = new DefaultHttpClient();
final HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
log.warn("Error " + statusCode + " for URL " + url);
return null;
}
final HttpEntity getResponseEntity = getResponse.getEntity();
final InputStream content = getResponseEntity.getContent();
return content;
} catch (final IOException e) {
getRequest.abort();
log.warn("Exception in downloadXmlFileStreamUsingUrl, error for URL " + url + e, e);
}
finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
client.getConnectionManager().shutdown();
}
return null;
}