Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

android - Loading Image using AsyncTask

I am trying to create a custom List Adapter which has an Image for every item it needs to download from the internet. When I first enter the Activity - the app freezes for a while till the images are downloaded and then the Activity List is loaded.

As I can make out the images are being downloaded before the activity loads. How can I download the images after the activity has loaded. I think I need to use Async Task. But since I am loading the images in the Custom Array Adapter not sure how to do it.

This is my Custom Adapter's getView():

public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.list_item_default, null);
        }

        Item p = items.get(position);

        if (p != null) {

            TextView list_title = (TextView) v.findViewById(R.id.list_title);
            TextView list_description = (TextView) v
                    .findViewById(R.id.list_description);
            TextView list_timestamp = (TextView) v
                    .findViewById(R.id.list_timestamp);
            ImageView list_image = (ImageView) v.findViewById(R.id.list_image);

            if (list_title != null) {
                list_title.setText(p.getItemTitle());
            }

            if (list_description != null) {
                list_description.setText(p.getItemDescription());
            }

            if (list_timestamp != null) {
                list_timestamp.setText(p.getItemTimestamp());
            }

            if (list_image != null) {
                Log.d("bMobile", "inside getView() image");
                try {
                    URL imageURL = new URL(p.getItemImage());
                    HttpURLConnection con = (HttpURLConnection) imageURL
                            .openConnection();
                    InputStream inputStrem = con.getInputStream();
                    Bitmap image = BitmapFactory.decodeStream(inputStrem);
                    if (null != image)
                        list_image.setImageBitmap(image);
                    else
                        Log.d("bMobile", "Bitmap is Null");
                } catch (Exception e) {
                }
            }
        }

        return v;
    }

AsyncTask:

public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {

    ImageView imageView = null;

    @Override
    protected Bitmap doInBackground(ImageView... imageViews) {
        this.imageView = imageViews[0];
        return download_Image((String)imageView.getTag());
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }

}
    private Bitmap download_Image(String url) {

        Bitmap bmp =null;
        try{
            URL ulrn = new URL(url);
            HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
            InputStream is = con.getInputStream();
            bmp = BitmapFactory.decodeStream(is);
            if (null != bmp)
                return bmp;

            }catch(Exception e){}
        return bmp;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

"the app freezes" - This is because you are downloading the images on the event thread or UI Thread. You should never do that. All blocking operations,long running operations, network operations, should be run on a separate thread. Yes you can use asynctask to do the image loading which should fix the issue.

Two options you can do to solve the issue is

  1. Use WebImageView from droid fu library at http://brainflush.wordpress.com/2009/11/23/droid-fu-part-2-webimageview-and-webgalleryadapter/ WebImageView uses caching as well so you dont need to download images again which you have already downloaded. Downloading images are expensive and consume data. I used WebImageView and was able to load images in list. It took me just about 20 mins to get it all working, so you know its easy integrating it.

  2. Second option is to use async task . Please check Android : Loading an image from the Web with Asynctask . There are lot more info in stackoverflow regarding how to do this.

Any time your UI hangs, you should have a creepy feeling, that you are doing something on the UI thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...