Saturday, April 11, 2009

How to download and display Images in android

/*
This example helps you to display the remote images in android. The progress bar will be displayed when application downloading the image. Progress bar will be stopped when the download completes and the Image will be displayed. This is also a good example for using thread in the background.. I Hope it helps..
*/

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class ViewStorageImage extends Activity {
      private String url;
      ImageView iv;
      Thread t;
      Bitmap bm;
      ProgressDialog dialog;
       @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            showDialog(0);
            setContentView(R.layout.storageimage);
            url = "http://.........";//enter the url here..
            iv=(ImageView)findViewById(R.id.storageactualimage);
            t=new Thread() {
                  public void run() {
                        viewImage();
                  }
            };
            t.start();
      }
      @Override
      protected Dialog onCreateDialog(int id) {
            switch (id) {
                  case 0: {
                        dialog = new ProgressDialog(this);
                        dialog.setMessage("Please wait while loading...");
                        dialog.setIndeterminate(true);
                        dialog.setCancelable(true);
                        return dialog;
                  }
            }
            return null;
      }
      private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                  Bitmap image=(Bitmap)msg.obj;
                  ImageView iv=new ImageView(this);
                  iv.setImageBitmap(image);
                  setContentView(iv);
            }
      };
      public void viewImage() {
            try {
                  URL myURL = new URL(url);
                  final BufferedInputStream bis = new BufferedInputStream(myURL.openStream(), 1024);
                  final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                  BufferedOutputStream out = new BufferedOutputStream(dataStream,1024);
                  copy(bis, out);
                  out.flush();
                  final byte[] data = dataStream.toByteArray();
                  BitmapFactory.Options bfo = new BitmapFactory.Options();
                  bfo.inSampleSize = 2;
                  bm = BitmapFactory.decodeByteArray(data, 0, data.length, bfo);
                  bis.close();
                  removeDialog(0);
                  Message myMessage=new Message();
                  myMessage.obj=bm;
                  handler.sendMessage(myMessage);
            }
            catch (Exception e) {
                  finish();
            }
      }
      static final int BUFF_SIZE = 1024;
      static final byte[] buffer = new byte[BUFF_SIZE];
      public static void copy(BufferedInputStream in, BufferedOutputStream out) throws IOException {
            try {
                  while (true) {
                              synchronized (buffer) {
                              int amountRead = in.read(buffer);
                              if (amountRead == -1) {
                                    break;
                              }
                              out.write(buffer, 0, amountRead);
                        }
                  }
            }
            catch(Exception e){
                  if (in != null) {
                        in.close();
                  }
                  if (out != null) {
                        out.close();
                  }
            }
            finally {
                  if (in != null) {
                        in.close();
                  }
                  if (out != null) {
                        out.close();
                  }
            }
      }
}

16 comments:

  1. Is there a layout xml file as well for this sample?

    I noticed an R.layout.storageimage and R.id.storageactualimage.

    I'm new to andriod and these were throwing compiler errors for me and I'm not quite advanced enough to fill in the gaps

    ReplyDelete
  2. Even i am getting compilation error. Could you please share layout.xml

    ReplyDelete
  3. Latest reviews and news about android phones, free droid app and android mobile

    android mobile

    ReplyDelete
  4. Ramesh, this looks pretty cool. Could you share the xml file with the layouts?
    Also, I'm getting an error in the handler, in line...
    ImageView iv=new ImageView(this);
    ... any ideas?
    Thanks a lot!

    ReplyDelete
  5. Nice Tutorial........Thanks...

    ReplyDelete
  6. I'm getting an error in handler,in line...
    ImageView iv=new ImageView(this);

    Please answer me.

    ReplyDelete
  7. I too am getting an error in handler,in line...
    ImageView iv=new ImageView(this);
    Please answer me too.

    ReplyDelete
  8. I resolved the issue with ImageView(this) and modified it to ImageView(ViewStorageImage.this). The problem was that the Handler class is effectively an inner class and you need to explicitly reference the outer class.

    Also note that the Android manifest needs the INTERNET permission to access the URL.

    ReplyDelete
  9. HI ALL,
    Also note that the Android manifest needs the INTERNET permission to access the URL.

    ? what permission ?, android.permission.INTERNET ?, android permission.MOUNT_UNMOUNT_FILES ??
    i have an error in line " final BufferedInputStream bis = new BufferedInputStream(myURL.openStream(), 1024);" the application is in loop mode... please help

    ReplyDelete
  10. where is the xml files (layouts)

    ReplyDelete
  11. the image is not displaying

    ReplyDelete
  12. hi frendz !! can any body tell me why does the app close without any error,neither it display the image.
    there is no compile error in it too..?

    ReplyDelete
  13. i want to give interest statement such as song...then my app download/show the links for the songs.
    how can i achieve it anyone can help? thanks in advance.

    ReplyDelete