Best practice recycling images android - android

I have a game where four images are displayed, the user answers a question and then re-display four different ones. I display images creating a Bitmap and load them from assets folder.
Which is the best practice, call the method removeAllViews() of the view and recreate the images or change pictures with setImageBitmap. Thanks.

Look at this source code: android.widget.ImageView#updateDrawable(Drawable)
Old Drawable will be replaced by the new one. Garbage Collector frees the allocated memory sometime later. Unless you are holding somewhere the reference to the old image (List, Map, etc...).

Related

Implementing a global LruCache vs many local LruCaches

Several Activitys in my app display images in a ListView where each row of the ListView contains an ImageView.
An example of this would be a search screen where the user searches, gets results, and a picture of each result is shown.
I'm trying to weigh the cost/benefits of implementing a global LruCache vs having each Activity contain its own local LruCache.
Here are my two main problems. Both revolve around the fact that my app is quite large, meaning there are quite a few screens which show these images. Also, my app has the popular side menu way of navigating. Because of this, I could open the menu, tap Activity B, open the menu, tap Activity A, open the menu... etc. and create an Activity stack of ABABABABABABABAB indefinitely.
Global
Won't Activitys with ImageViews using Bitmaps from a global LruCache contain references to these Bitmaps? Suppose the user navigates away from this Activity by clicking some Button. That Activity is now on the Activity stack and still holds references to those Bitmaps. If the LruCache pops a Bitmap off, can that Bitmap really be reclaimed when an ImageView in some Activity on the stack holds a reference to it?
I had previously created my own custom cache. If I called recycle() on a Bitmap and then the user hit the back button to go back to some Activity on the stack that contained an ImageView set to that Bitmap, the app would crash. This is why I believe ImageViews on Activitys on the stack still hold references to Bitmaps.
Local
As I mentioned earlier. My app is quite large, and side menu style of navigation allows the user to create rather large Activity stacks. This would create a lot of LruCaches. And, since you have to declare the size of the LruCache when you initialize it, there wouldn't seem to be any good way of picking a size.
Thoughts? Suggestions?
At this point I think I have to do global, but I don't know how to solve the Activity stack reference problem. I can't imagine this isn't a problem many apps haven't run into. I don't know why I'm not finding information about it.
I'm trying to weigh the cost/benefits of implementing a global
LruCache vs having each Activity contain its own local LruCache.
Global LruCache is the way to move forward, since the same set of bitmaps might be referred in different activity instances. The LruCache can be defined part of Application. If the activity stack can host multiple instances of the same activity (like ABABABAB..), then creating a LruCache locally in that activity will be a bad idea. Very soon Out Of Memory situtation will be reached, as LruCache in each activity instance reserves the defined amount of memory in Dalvik VM. Assume, application memory is 32Mb and you decide LruCache size as 4Mb i.e. 1/8th. Now when we create nearly 7 instances of Activity A, then memory consumption will go to 7*4=28Mb, that itself might trigger OOM.
Won't Activitys with ImageViews using Bitmaps from a global LruCache
contain references to these Bitmaps?
Yes ImageView will also have a strong reference to the bitmap. If the reference is maintained in LruCache, then the reference count will be 2 at that moment.
If the LruCache pops a Bitmap off, can that Bitmap really be reclaimed
when an ImageView in some Activity on the stack holds a reference to
it?
No the bitmap memory can't be reclaimed, as still some ImageView is have a strong reference to it.
At this point I think I have to do global, but I don't know how to
solve the Activity stack reference problem.
LruCache main role is holding strong reference to the bitmap which are more frequently used. So that if there is no strong reference held by any ImageView, the bitmap is prevented from being garbage collected.
Also remember, for Android 2.3.3 and lower versions, you need to implement reference counting mechanism, in order to recycle the bitmaps.

Images not loaded into ListView when scrolling fast

I have a long ListView in which there is an ImageView for each row. It displays the correct bitmaps if I slowly scroll the list (each row has different icon to show).
The problem comes up when I scroll the ListView fastly. It happens that many images are not loaded into their ImageView, leaving it transparent. Even the ones that were previously shown scrolling the list slowly.
Here is the code inside the getView() method that should display the icons:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
String name = ... //custom code to get the icon name to show
Bitmap bitmap = BitmapFactory.decodeFile(getIconsDir() + name + getIconsExt(), options);
holder.imgIcon.setImageBitmap(bitmap);
I'm recycling the convertView in the getView() method of the adapter.
I know for sure that the bitmap exists in that location.
imgIcon is the ImageView referenced by the ViewHolder of the row.
I've also tried to use image loaders (like Picasso) but I got the same result.
Does anyone have experienced this before?
Do not do bitmap decoding in adapter's getView(). It will Cause ListView to lag and also fill up RAM very fast.
You should:
Use a size limited, in-memory cache to hold onto bitmaps.
Decode and Load images in Views asynchronously.
ListView re-cycles the views, and device memory may not hold all the bitmaps loaded all the time. Even Image loading Libraries face that issue.
Yes, there are performance issues with images in ListViews.
But prefetching the images in any way is a could approach to avoid the calls to read operations on the file system and decoding of binary data.
I extinguish that you are storing your viewholder in the convertviews - tag.
Loading images from disk is a slow operation, and so is decoding them from whatever compressed format they're stored in (like JPG or PNG) into a Bitmap. So ideally, it shouldn't be done in getView() on the main thread. Also, they take up a lot of memory.
If these "icons" are static, you should just include them as drawable resources and then use ImageView.setImageResource. Then the OS will figure out how to load them most optimally (plus, that way you'll have the correct resolution for the given screen).
If the icons are not static (e.g. loaded from the network), I recommend using an in-memory cache with an asynchronous loader, but make sure it's limited in size and/or uses weak references (but beware: Android generally advises against using weak/soft references, especially for bitmaps, since the memory allocated for bitmaps is in native code, so the garbage collector doesn't know how much memory those images are really taking up and it may decide not to collect them even if it's running low on memory... because it thinks they're small).

how to clear memory when it is full because of using too many backgrounds in android

Hi guys i am new to android and i posted a question a week ago in this link which basically stated that i was getting a java.lang.outofmemory error when i was using a lot of different backgrounds for my activities.
why am I getting errors when I use different backgrounds in xml
So as a new developer I have searched and searched for a solution as to how to clear the memory as i go from activity but none have been clear or precise. Then i stumbled across this site http://androidactivity.wordpress.com/2011/09/24/solution-for-outofmemoryerror-bitmap-size-exceeds-vm-budget/
which described exactly what i was going through except they use 10 activities and i am only using 4. However when i implemented his code it my project i ended up with null pointer exceptions and after fiddling with his code I ended up back were i started with the same out of memory error.
So can anybody direct me to someone who can show me how to have as many backgrounds as i want with out running out of memory. Or does android as great as it is does not let you simply use more than a certain amount of backgrounds? help?
It's not that there is a limit on the amount of backgrounds, but each background image you load is a loaded into memory as a bitmap and held there until the activity is destroyed. If you are opening multiple activities one after another, each background image will need to be held in memory and so eventually you will get an out of memory exception.
If you set a large background image, you will also experience some blocking on the ui thread, while the image is loaded into memory.
One way around this that worked for me was to use an imageloader. This decodes the image off the ui thread, caches it on disk, loads it into memory and if memory is running low, will clear an image from memory and fallback to the disk cache. You may get a slight delay/fade in as the image is loaded but this is not so bad visually, and when loaded once, will load straight away if you go back to that activity.
Check out Picaso Picasso which is really easy to implement and a great api or Universal Image Loader.
My layouts were all RelativeLayouts and the first child (will be behind all other views) was an ImageView with scaleType centercrop and width and height set to match_parent. When each activity loads (onCreate), just grab a reference to the imageview in your layout and set the required background image using your ImageLoader of choice.
The other option is to have multiple copies of your background image in your resources, with each one resized to perfectly fit your resolutions of choice (drawable-mdpi/-hdpi/-xhdpi etc). This way, you ensure you are never loading images that are way bigger than you need to be displayed and your app will be more forgiving in terms of memory consumption.

Reclaiming memory from GridView Bitmaps that are off-screen and are not likely to be used

I have a GridView that I use to display images from an API.
The normal user behavior is to go to the bottom and pull more results.
I plan to scale the bitmaps down, but there will be many of them.
Therefore, I think it might be safe to delete images that are many pages above the current page.
Are the old images deleted by the GridView at some point?
The normal usage is to use the view cache, which looks like the GridView is holding on to them.

android load drawables into cache

I have an activity which is playing a beat and alternating drawables from my drawables folder in tandem. Unfortunately the loading of the drawables is too slow and it goes out of sync.
Does anyone have a proposed solution?
I think it's common to load all your bitmaps ahead of time (perhaps with BitmapFactory.decodeResources()). Once loaded, just hang on to those references for your drawing.
Does that answer your question?
The answer is in the question. You can create a class that acts like a bitmap cache that uses a backing HashMap to save references to the decoded bitmaps. The simplest thing to do is to cache the full size bitmap and just key it with the generated int id from R.java. I did something similar, but I included the resizing logic and keyed it by a string in the form resourceid:width:height. You can provide a remove method and a clear method if you want to make sure you keep your memory down, but remember to recycle your bitmaps for older versions of the OS.

Categories

Resources