PeterW
PeterW

Reputation: 51

Error removing Bitmaps[Android]

I am working on a simple application that draws small bitmaps onto the screen, and have a little trouble clearing the screen. My bitmaps are stored in an ArrayList called _graphics, and I need to clear the screen, so I clear my ArrayList. This works fine in clearing the screen, however after a while my app force closes.

If I draw around 50 bitmaps on the screen, it will force close the first time I clear it, however if I only draw 5, I can get about 10 Clears before it crashes. I assume this is something to do with the GC not clearing the bitmaps correctly. Does anyone have an ideas on the subject?

Upvotes: 0

Views: 1229

Answers (2)

Impression
Impression

Reputation: 727

OK - now the stack trace is attached: ConcurrentModificationException You modify the ArrayList from different threads or iterating over it. Either you have to synchronize the access or use another collection like ConcurrentHashSet.

But maybe the following (my origin answer) will be interesting too :p

Sounds like, that you are caching the real Bitmap objects with the whole pixel data -> I guess, you got OutOfMemoryException

The garbage collector is an asynchronous operation and if you clear your bitmap array, the bitmaps are not unloaded from memory instantly. If you are inserting new ones, it can happen, that the old are still in memory and the new ones gets loaded too.

Solution: Do not cache the bitmaps in that way, you are doing.

They are different things, you can try (depends on yout concrete scenrario):

1) If they are stored on SD card or something else, cache only the path to the bitmaps in your collection and load them, if they are needed for drawing.

2) Use Drawable objects instead of bitmaps - theys have some interesting methods and algorithm for optimized access to the bitmap data.

3) To optimize the performance use something like SoftReference or similar - maybe WeakRefernce. SoftReferences can be unloaded by the GC on demand (when memory gets low). In that case you have to check, whether the soft refence is null or still exists. E.g:

ArrayList<SoftReference<Bitmap>> _graphics = new ArrayList<SoftReference<Bitmap>>();
...

for (int i = 0; i < _graphics.size(); i++)
{
    Bitmap b = _graphics.get(i).get();
    if (b == null)
    {
        b = loadFromSomewhere(i);
        _graphics.add(new SoftReference<Bitmap>(b), i);
    }
    ... do something wwith your bitmap
}

This code snipet is not tested or written with an Java Editor (please excuse typing errors or wrong method signatures).

Upvotes: 1

PeterW
PeterW

Reputation: 51

Going over the Logcat File I seem to have found the error (New Android Dev :p Didn't even know it existed). It was due to a ConcurrentModificationException. Everything seems to be working now =D

Upvotes: 1

Related Questions