Home » Android » android – Consensus on lazy loading Bitmaps in an Adapter (emphasis on Bitmap.recycle())

android – Consensus on lazy loading Bitmaps in an Adapter (emphasis on Bitmap.recycle())

Posted by: admin May 14, 2020 Leave a comment


I see a truckload of suggestions for this, but none (that I’ve found) take all factors into account, the factors being:

  1. Asynchronous downloading, without duplication (of downloaders and Bitmaps), with canceling downloads/assigning of images that would no
    longer be needed anyway
  2. An adapter can have multiple Views for the same ID (calls to getView(0) are very frequent)
  3. There is no guarantee that a view will not be lost instead of recycled (consider List/GridView resizing or filtering by text)
  4. A separation of views and data/logic (as much as possible)
  5. NOT starting a separate Thread for each download (visible slowdown of UI). Use a queue/stack (LinkedBlockingQueue?) and thread pool, or
    somesuch…. but need to end that if the Activity is destroyed.
  6. Purging Bitmaps sufficiently distant from the current position in the list/grid, preferably only when memory is needed
  7. Calling recycle() on every Bitmap that is to be discarded.
  8. External memory may not be available (at all or all the time), and, if used, should be cleared (of ONLY the images downloaded here) asap.
    Also consider Activity destruction/recreation by Android.
  9. Data being changed: entries removed (select in list, button to remove, immediate refresh) and added in a background Thread (list
    refreshed on demand). Already downloaded Bitmaps should be kept, as
    long as the entries they’re linked to still exist.
  10. (optional) do not rely on notifyDataSetChanged (which, afaik, refreshes all visible, potentially very complex, list items) for
    updating a single ImageView
  11. setTextFilterEnabled(true) (as in ArrayAdapter. Its implementation of Filterable replaces the data array visible to the other Adapter
    methods, therefore changing indexes of the views, so they cannot be
    used as IDs to link to the Bitmaps).
  12. Usable in ExpandableList (affects the order the thumbnails are shown in)

Please forgive me if this had been answered. I’ve searched for months, and not found a solution.

The requirements seem reasonable to me, but each one adds a dimension of difficulty, especially Bitmap.recycle, which needs to be called during operation and on Activity destruction (note that onDestroy, even onStop might not be called).
This also precludes relying on SoftReferences, which could have taken care of some of the other points.
Yes, it is necessary, or I get OutOfMemoryError even after any number of gc, sleep (20s, even), yield and huge array allocations in a try-catch (to force a controlled low memory situation).
Search for “OutOfMemoryError: bitmap size exceeds VM budget” or “android bitmap recycle”.
Yes, I am resampling the Bitmaps.

How to&Answers: