0

I have been following a tutorial that remotely downloads an image to an imageview, but i'm not sure how to add a progress dialog (image or something) to show the user that image is downloading, instead of just a blank screen.

Hope someone can help

 ImageView imView;
 String imageUrl="http://domain.com/images/";
 Random r= new Random();
/** Called when the activity is first created. */ 
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,
            WindowManager.LayoutParams.FLAG_FULLSCREEN );

    setContentView(R.layout.galleryshow);

    Button bt3= (Button)findViewById(R.id.get_imagebt);
    bt3.setOnClickListener(getImgListener);
    imView = (ImageView)findViewById(R.id.imview);
}    

View.OnClickListener getImgListener = new View.OnClickListener()
{

      @Override
      public void onClick(View view) {
           // TODO Auto-generated method stub


           int i =r.nextInt(114);
           downloadFile(imageUrl+"image-"+i+".jpg");
           Log.i("im url",imageUrl+"image-"+i+".jpg");
      }

};


Bitmap bmImg;
void downloadFile(String fileUrl){
      URL myFileUrl =null;          
      try {
           myFileUrl= new URL(fileUrl);
      } catch (MalformedURLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
      }
      try {
           HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
           conn.setDoInput(true);
           conn.connect();
           int length = conn.getContentLength();
           InputStream is = conn.getInputStream();

           bmImg = BitmapFactory.decodeStream(is);
           imView.setImageBitmap(bmImg);
      } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
      }
 }
}
Lucy
  • 239
  • 1
  • 3
  • 14
  • Exact duplicate http://stackoverflow.com/questions/2735102/ideal-way-to-cancel-an-executing-asynctask/2740204#2740204 – Dharmendra Aug 24 '11 at 15:18

2 Answers2

1

You should look at this : asynctask is the way to go.

Android : Loading an image from the Web with Asynctask

Regards, Stéphane

Community
  • 1
  • 1
Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • Thanks Stephane, but i'm a android newbie and the link you provided is just to technical for me to administer. I think it would help me if i could apply this progress dialog to the code i'am already using, so at least i can get my head around how everthing is working. Is it possible for you to show me how i could implement it in the code i provided. Thankyou, Lucy – Lucy Aug 24 '11 at 15:23
0

You need to look at ProgressBar class and basically use that while the image is loading. Alternatively you could put default image while the image is being downloaded.

To put the progress bar in your code, the easiest basically just flip their visibility in the layout.

  1. In your layout, you have two things. One placeholder for ProgressBar and the other is for the image
  2. The progressbar is set to VISIBLE initially and the image to GONE
  3. After you execute the AsyncTask (see below), you need to flip the visibility. Basically change the progressBar to GONE and the image to VISIBLE

Here is what you should try to do. Check the NOTE and TODO comment in the code. Note: I just modified your code, but haven't run it, but this should be enough to illustrate the idea.

Some key points:

  1. Long running task that might block UI Thread should get executed in AsyncTask. In your case, this would be downloading the image
  2. Post execution that needs to be handled in UI Thread should be handle in postExecute()
  3. Doing e.printStacktrace() during catching Exception is not a good practice. Without appropriate handles, this exception is not being handled correctly and might cause bugs in the future. In addition, during production, this information doesn't help you at all when bugs occur on the client's side since it is merely printing out in the console


    View.OnClickListener getImgListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View view) {
            // NOTE: here you need to show the progress bar, you could utilize ProgressBar class from Android
            // TODO: Show progress bar

            AsyncTask asyncTask = new AsyncTask() {
                @Override
                public Bitmap doInBackground(Void... params) {
                    int i =r.nextInt(114);

                    // NOTE: move image download to async task
                    return downloadFile(imageUrl+"image-"+i+".jpg");
                }

                @Override
                public void onPostExecute(Bitmap result) {
                    // TODO: hide the progress bar here 
                    // and flip the image to VISIBLE as noted above
                    if(result != null) {
                        imView.setImageBitmap(result);
                    } else {
                        // NOTE 3: handle image null here, maybe by showing default image
                    }
                }
            };

            // NOTE: execute in the background so you don't block the thread
            asyncTask.execute();
        }
    };

    // Change the return type to Bitmap so we could use it in AsyncTask
    Bitmap downloadFile(String fileUrl){
        URL myFileUrl =null;          
        try {
            myFileUrl= new URL(fileUrl);
        } catch (MalformedURLException e) {
            // NOTE: You should not have e.printStacktrace() here. In fact
            // printStacktrace is a bad practice as it doesn't really do anything
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            int length = conn.getContentLength();
            InputStream is = conn.getInputStream();

            Bitmap bmImg = BitmapFactory.decodeStream(is);

            // return image this to the main Thread
            return bmImg;
        } catch (IOException e) {
            return null;
        }
    }

momo
  • 21,233
  • 8
  • 39
  • 38
  • Thanks Momo for your in-depth answer. Very much apreciated. It all sounds a bit over whelming at the moment. (Newbie Shaking Here) I'm not entirely sure where to start. I will be looking over your notes and suggestions and try to implement one by one. You mention in your notes to get the progress bar from android, where do i find that? Sorry if i sound ignorant, i'm really nice when i'm not pulling my hair out trying to learn android! Thanks Again.. – Lucy Aug 24 '11 at 17:08
  • Luci, here is the link to the ProgressBar http://developer.android.com/reference/android/widget/ProgressBar.html that you could put in the layout and show while the image is downloading – momo Aug 24 '11 at 17:13