If you wish to download an image and display it on your screen in android refer the code below.
The code of the MainActivity is as shown below:
public class MainActivity extends AppCompatActivity {
Button load_img;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
load_img = (Button)findViewById(R.id.load);
img = (ImageView)findViewById(R.id.img);
load_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute(“http://www.meijergardens.org/assets/img/butterfly.png”);
}
});
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(“Loading Image ….”);
pDialog.show();
}
protected Bitmap doInBackground(String… args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, “Image Does Not exist or Network Error”, Toast.LENGTH_SHORT).show();
}
}
}
}
Explanation
In our layout we are using a Button and an ImageView. Button is used to trigger the loading process and ImageView is used to display the image.
- In MainActivity we use AsyncTask to load the image from the url.
- In doInBackground we use BitmapFactory class to get the bitmap from the url.
- The onPostExecute is for displaying the bitmap in ImageView.
- The image url should be passed to the AsyncTask.
- When the Load Image Button is pressed the “LoadImage” AsyncTask is executed and Image is displayed in ImageView.
- Finally,we use display ProgressDialog while fetching data.
The output for the above code is as shown: