Downloading an image from url

No Comments

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;

protected void onCreate(Bundle savedInstanceState) {
load_img = (Button)findViewById(;
img = (ImageView)findViewById(;
load_img.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute(“”);
private class LoadImage extends AsyncTask<String, String, Bitmap> {
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(“Loading Image ….”);;

protected Bitmap doInBackground(String… args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());

} catch (Exception e) {
return bitmap;

protected void onPostExecute(Bitmap image) {

if(image != null){


Toast.makeText(MainActivity.this, “Image Does Not exist or Network Error”, Toast.LENGTH_SHORT).show();




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:


About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts

Leave a Comment