开发者

Android Help with adding a progress dialog while image loading?

开发者 https://www.devze.com 2023-03-30 16:50 出处:网络
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, inste

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 Au开发者_StackOverflowto-generated catch block
           e.printStackTrace();
      }
 }
}


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

Android : Loading an image from the Web with Asynctask

Regards, Stéphane


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;
        }
    }

0

精彩评论

暂无评论...
验证码 换一张
取 消