Jake
Jake

Reputation: 1332

OutOfMemoryError bitmaps android

I am caching my images in android and not sure how to reuse bitmaps as android suggest here: https://developer.android.com/training/displaying-bitmaps/manage-memory.html here is my code

final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;
    this.imageCache= new LruCache<String, Bitmap>(cacheSize){


         @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                return bitmap.getByteCount() / 1024;
            }

    };
    this.m_adapter = new ImageScreenAdapter(this, R.layout.imagelist_item, items, imageCache);
    setListAdapter(this.m_adapter);

this is the method I use to download my bitmaps

  private Bitmap downloadBitmap(String url, ProgressBar progress, int position) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    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);
            if(progress!=null)
            {
              RemoveImageResults(position);
              return null;
            }
            return BitmapFactory.decodeResource(getResources(), R.drawable.missingpic);
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = false;
                options.inDither = true;
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream,null, options);
                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 " + url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

and in my AsyncTask

  @Override
   protected void onPostExecute(Bitmap result) {
      final Bitmap Image=result;
       if(Image!=null)
           imageCache.put(imageUrl, Image);
       myActivity.runOnUiThread(new Runnable() {
           public void run() {

               imageView.setImageBitmap(Image);
               imageView.setVisibility(View.VISIBLE);

           }
         });

   }

   private Bitmap download_Image(String url) {
      return downloadBitmap(url, progress, position);


   }

But this could run out of memory if it gets up to 1000 images in my list adapter, so how do I reuse the bitmaps or recycle the unused ones? I am targeting android 3.0 or better and as android suggest I could use a Set> mReusableBitmaps; but I don't follow how to implement this.

Upvotes: 0

Views: 387

Answers (1)

James andresakis
James andresakis

Reputation: 5415

The best way to handle this issue is to implement some kind of lazy image loading where you have weak referenced bitmaps that can be recycled by the system easier. There is a ton of samples online and there is a very popular open source library on github that does all this for you. They even have callbacks that you can use to display a progress bar while your image loads and get rid of it when the image is done downloading. You can find it here : https://github.com/nostra13/Android-Universal-Image-Loader

Upvotes: 1

Related Questions