Как скачать и отобразить растровые изображения с AsyncTask

1

Я новичок с Android и последние пару дней. Я не могу найти причину проблемы:

У меня есть ActivityA с ListView. Каждый элемент в этом элементе ListView при нажатии откроется ActivityB, который покажет некоторое количество изображений, загруженных из Интернета, в ImageView. Итак, в ActivityB у меня есть цикл со следующим кодом, чтобы попытаться загрузить изображения:

ImageView ivPictureSmall = new ImageView(this);
ImageDownloader ido = new ImageDownloader();
ido.download(this.getResources().getString(R.string.images_uri) + strPictureSmall, ivPictureSmall);
ivPictureSmall.setPadding(3, 5, 3, 5);
linearLayout.addView(ivPictureSmall);

Класс ImageDownloader


public class ImageDownloader
{
    public void download(String url, ImageView imageView)
    {
            BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
            task.execute(url);
    }
}

Класс BitmapDownloaderTask


class BitmapDownloaderTask extends AsyncTask
{
    private String url;
    private final WeakReference imageViewReference;

    public BitmapDownloaderTask(ImageView imageView)
    {
        imageViewReference = new WeakReference(imageView);
    }

    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params)
    {
        // params comes from the execute() call: params[0] is the url.
        return downloadBitmap(params[0]);
    }

    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap)
    {
        if (isCancelled())
        {
            bitmap = null;
        }

        if (imageViewReference != null)
        {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }

    }

    protected Bitmap downloadBitmap(String url)
    {
        final DefaultHttpClient client = new DefaultHttpClient();
        final HttpGet getRequest = new HttpGet(url);

        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
                return null;
            }
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent();
                    final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            // Could provide a more explicit error message for IOException or IllegalStateException
            getRequest.abort();
            Log.w("ImageDownloader", "Error while retrieving bitmap from: " + e.toString());
        } finally {
            if (client != null) {
                //client.close();

            }
        }
        return null;
    }


    static class FlushedInputStream extends FilterInputStream
    {
        public FlushedInputStream(InputStream inputStream)
        {
            super(inputStream);
        }

        @Override
        public long skip(long n) throws IOException
        {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped 

When I clicked an item in the ListView in ActivityA, It correctly goes to ActivityB, and ActivityB shows the images. When I press the "Back" button on ActivityB to back up to ActivityA, then click again on an item in the ListView, I come to ActivityB and then I see am informed that the process closed unexpectedly.

When I attempt to debug, I noticed that the problem is in the linE:

final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));

Which is in a protected Bitmap downloadBitmap(String url) function.

I read about a bug in Android with BitmapFactory.decodeStream so I added FlushedInputStream to prevent it.

However, it seems to me this is not cause of the problem, since it was working when I first loaded ActivityB, but not the second time. Maybe I have a memory leak? (The pictures are big, and memory are not reycled after backing to ActivityA.)

If so, how can I clean up the associated memory? Or is the problem in something else?

For reference: My images are in .jpg format, I tried to convert them to .png, but had the same problems.

  • 0
    Ваш вопрос слишком длинный. Вы просите людей отладить ваш код для вас, и у большинства нет времени ...
  • 1
    Ну, я пытался дать всю соответствующую информацию .. Я думал, что есть некоторая проблема obviuos в коде, который я не вижу, потому что я новичок в Android и Java.
Показать ещё 1 комментарий
Теги:
android-asynctask
memory
download
bitmap

1 ответ

0

Вам следует использовать библиотеку загрузки изображений, например Picasso или Volley, чтобы выполнить тяжелую работу для вас.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню