Best way to free Android memory - android

I have been looking for a solution and I found many different opinions to solve my problem.
Here is what my app is doing:
It does a search in a database and it assembles n screens with n pictures. Each picture is an ImageButton and each one has its own image, action, etc. depending on what is stored in the database.
The created screens are thrown inside of a ViewFlipper.
Some items have "children".
So, if a user clicks on an ImageButton with a "child", it will search the database, get items, assemble the new screen(s) with ImageButtons with informations from database.
Then, Add this (these) new screen(s) to the ViewFlipper and keep a reference from the caller screen, so user may return to the caller screen if he wishes.
It will do the item 3 whenever an ImageButton has "children" according to the database.
It's easy to see that there will be lots of screens in the initial ViewFlipper.
It works flawlessly in my Asus EEE Pad Transformer. However if I try to run it in my Galaxy S (less memory) it will eventually crash (lack of memory exception) if I keep on browsing screens.
What's the best way for me to free up memory in this situation?

It is probably not going to be easy, but if you want to save memory - save on the views. Instead of building all the views in advance, build only the ones you need, and manage the flipping manually. After all, you only need to show one image at a time, so prepare that, and perhaps the one before that and the one after that for quick flipping, but don't prepare everything else before needed.

Related

How to cope with jitter when using Android-Universal-Image-Loader in a ListView?

I'm using Android-Universal-Image-Loader in a ListView of mine and I'm trying to find the best solution to following:
using resetViewBeforeLoading is necessary or else I get the same image in my ConvertViews, but this causes jitter, unless..
I use PauseOnScrollListener which is otherwise great, except that it shows a blank in some ConvertViews even for images that are already downloaded (I'm using memory and disk caches), so it's confusing to the user who sees a blank for an image they saw only 2 swipes ago
So it seems that I can't get an instant image load (for already-downloaded images) on scroll without jitter, even for images in memory, is this about right? Is there a better or more standard way to do this? (Vertical list-view showing screen-width images, sort of like the Instagram app, which does it buttery-smooth)
Otherwise, is there a way to lengthen the number of convertViews in my ListView to prevent unnecessarily aggressive re-use?
Thanks in advance

Preparing LruCache in Appwidget

i have an appwidget which starts an activity as user clicks it.
In my Activity i have a gridview containing relatively small Drawables(Images, because drawable could be mor than just Images) but user can size them.
I noticed that it takes too Long to size them at runtime when Scrolling trough the gridview.
I want to prepare an lruCache only one time in my appWidget's onUpdate which is called at the very beginning when the user places the appwidget on the Screen.
The problem
When i define an lruCache in my appWidget with
private final int lruCacheSize = (int) (Runtime.getRuntime().maxMemory()/1024);
private LruCache<String, BitmapDrawable> myLruCache;
...
myLruCache = new LruCache<String, BitmapDrawable>(lruCacheSize) {
#Override
protected int sizeOf(String key, BitmapDrawable value) {
// TODO Auto-generated method stub
return super.sizeOf(key, value);
}
};
Will it only exist as Long as the process exist of the appWidget? Or does the Cache-File from lruCache stays in my cacheDir of my app? Or will it be deleted after the process of the appWidget is finished? If it does exist over the process-lifetime of my appWidget, how can i Access it from my Activity?
I don't want to create everytime the user clicks on the appWidget a LruCache and fill it up with all the relatively small Images the gridview will Need later. I want to do it once, or if user clears the Cache which will be checked every hour(to save battery).
The Question
How can i achieve that? Or is there a much better/ simpler way.
Time is not really (if it happens once at the very beginning) the Problem, i notify the user that the Cache is being prepared when placing the appWidget on the Screen.
Any help is appreciated.
Update regarding CommonsWare answere
Use Traceview to determine specifically why your implementation is slow.
The app Scrolling is slow because i provide three sizes (small, medium, large) and i scale them at while Scrolling trough my gridview.(Because it would take several seconds to scale them once at activity Startup, so i don't want that).
See here what i do in my imageview which will later Show the drawable(which is an appIcon):
android:scaleType="fitXY"
android:adjustViewBounds="true"
This causes the lag because i do this for everyimage depending if selected scale size is small medium or large.
There is no "Cache-File" in your code.
So then i i'm misunderstanding something. Doesn't the lruCache create an Cache-File in the Cache-Directory of my application? If not how does in works?
First, you cannot force the user to install the app widget. Work on solving the actual performance problem, rather than trying to build some optimization that will not help all users.
My "app" is only an appwidget. There is not appIcon like at FaceBook. It is only an appWidget when he doenloads my app. Which starts an activity when you click on the button.
Second, your process can readily be terminated milliseconds after onUpdate() completes. Do not fill a cache, only to have it never be used.
I want to use the Cache which i want to fill with the Drawables in the onUpdate of the appWidget, and then i want to use These Drawables from the Cache in my activity. So i don't understand why i never would use the Cache? Maybe i'm misunderstanding something.
Picasso would give you better performance from the user's standpoint.
Does it fit my Needs after the update right now?
---------------------------------------------------------------------------------------------
Update 2
Since the scaling should be done by the GPU and take microseconds, I have difficulty believing that is your problem. What specifically did Traceview show you that made you think that scaling has something to do with this?
I noticed that the Scrolling is very fluid at medium size because that's nearly the origin size of the appIcon from the PackageManager. If scroll trough large, where only 2 or 3 appIcons are displayed per row (at medium there are 5 or 6 displayed but it is much more fluid)m it lags. (With the same logic behind it). So the only Logical answere can be scaling in the XML at the ImageView. As i commented that XML-Scaling out and scaled the appIcons to the size Large and put them directly scalled to to my Adapter for GridView it runs really smooth( Only one or to really small lags at the beginning because convertView is null??)
onUpdate() will be called much more frequently than the user will actually use your app widget.
That's right after every onclick or at the specified time. But i check if the Cache has been cleared or not, if not don't Change anything, if so load Drawables to Cache.
I noticed that it takes too Long to size them at runtime when Scrolling trough the gridview.
Use Traceview to determine specifically why your implementation is slow.
Will it only exist as Long as the process exist of the appWidget?
It will only exist for the lifetime of the process of your app.
Or does the Cache-File from lruCache stays in my cacheDir of my app?
There is no "Cache-File" in your code.
I don't want to create everytime the user clicks on the appWidget a LruCache and fill it up with all the relatively small Images the gridview will Need later. I want to do it once, or if user clears the Cache which will be checked every hour(to save battery).
First, you cannot force the user to install the app widget. Work on solving the actual performance problem, rather than trying to build some optimization that will not help all users.
Second, your process can readily be terminated milliseconds after onUpdate() completes. Do not fill a cache, only to have it never be used.
Or is there a much better/ simpler way.
Use Traceview to determine exactly where your problem lies. Then, solve that problem. For example, the problem could be that you are loading these images on the main application thread, and using a library like Picasso would give you better performance from the user's standpoint.
The app Scrolling is slow because i provide three sizes (small, medium, large) and i scale them at while Scrolling trough my gridview
Since the scaling should be done by the GPU and take microseconds, I have difficulty believing that is your problem. What specifically did Traceview show you that made you think that scaling has something to do with this?
Doesn't the lruCache create an Cache-File in the Cache-Directory of my application?
No.
If not how does in works?
It is an in-memory cache.
So i don't understand why i never would use the Cache?
onUpdate() will be called much more frequently than the user will actually use your app widget.

"Best" way for loading many items

I'm making an ListView in my app which over time could contain hundreds of items. Are there any "best" methods of loading lots of data?
My idea is to load it in chunks (say 10-20 items). Load the first chunk, then when the user is about halfway through scrolling, load the next chunk, add it to the bottom of the list (and make sure the list scroll offset doesn't jump about).
Some other ideas I had just didn't like so much were accepting the cost of a large http call and load all the data at once, but just load it in chunks as they scroll, or maybe add a "Next x items" button at the bottom, or loading all the items into the list at once and having one large list I don't need to keep track of.
I personally like my original idea, I was just wondering if there is a preferred method or doing this, and if there are any performance issues I could have.
The data in question will be a JSON string, and each item will display some title text, a date, the author of the item, and an image which will be downloaded using the Picasso library.
Your initial idea is my preferred approach because it works very well in most situations.
The second one may work well, but the problem is, the "large" data concept is relative across devices. For powerful devices you may load 2000 items at once, but it will kill older, slower phones. Also, if you're loading 2000 items when the use case of that ListView is to choose one in the first 100, you are wasting bandwith.
The first approach is very scalable: You really don't care if there are 5 items or 50 million, you just load chunks as the user consumes them. The memory usage is consistent. Coupled with ListView's view recycling, this will have a small memory footprint.
To say something positive about the second approach: Maybe in a use case when the ListView always has the same data, and it rarely changes, for example, an image library, you may want to load all the data at application start and cache it, so you never have to do network requests while the user is using the app. If the data size is not huge, I'd go for this second approach. But always having in mind that there's a critical size after which you will need to page!
Basically you can load all items once and show them all (if you will use ViewHolder pattern and lazy image loading using Picasso - everything should be ok). If you have some business logic which force you to show data by pages - you can follow the way that you described first.
If you will show all data - you can add search by list for better UX(you also can do it when you have pages but it will be more tricky).
Some time ago I wrote an article on similar topic:
http://developer.samsung.com/android/technical-docs/Batch-loading-list
The article comes also with a small library of common classes.
Maybe you will find it helpful.
Cheers,

If I set some heavy layouts to null does it cause garbage collection soon?

My android app contains some images for list backgrounds and other stuff ( images have size between 2KB and 20KB), I need to put six layouts, at one time only one is visible (4 of them contains two expandable listviews) in one activity. Lists are not very long, around 10 items each. When I start and after some time go to another actvity (from this heavy go to new without finish) I got OutOfMemory exception. When I build my app it is only around 2.5 MB.
I have lot of setBackground functions and 5 ViewPagers. If I set some layouts to null does it cause garbage collection soon ? Did anyone have similar problem whwn dealing with lot of images inside app ?
I suspect that when you set the backgrounds you are just calling setBackground(...)
I suggest you load the bitmaps according to this example.
something along the lines of: setBackground(decodeSampledBitmapFromResource());
It is bad practice but you can always call System.gc(); to throttle/force a GC when you've release a resource.

How to clean up bitmap resources

I wanted to ask this question that was asked a few times before. Sorry if I am re-itterating but it is not clear to me as to what is the best solution here.
The question is "how to clean ImageView bitmap resource after its been used so we don't have references to it in memory?".
Here is an example:
Screen 1 redirects to Screen 2
Screen 2 contains control A (preview of large photo)
Control A contains ImageView B
ImageView B is set when control A is initiated
Everything works fine the first time around. Once control A is done I redirect from Screen 2 to Screen 1. At this point all references of control A or ImageView B or Bitmap that its using should be dead. THEY ARE NOT!!!
I've tried all kinds of solutions including bitmap.recycle(), adding finalize() into Control A, System.gs() and nulling control in variouse places such as onStop() and onDestroy(), and everything else that's on screen 2, nothing works!
The problem is when I revisit the screen second time around so going from screen 1 to screen 2 (i.e. creating preview of photo again) I get out of memory exception. It is my understanding that the reference of the previous bitmap is not cleaned up.
How do I KILL it just before I redirect back to Screen 1?
One thing I noticed. If I reduce the size of the photo by, say cropping or making a smaller size of the image everything goes smooth, few times... before I get same issue. So basically it just takes a bit longer to fill up.
I would really appreciate some solution here as this is critical.
You probably have a memory leak , this video might help you in finding the problem Google I/O 2011: Memory management for Android Apps.
Note : pre 3.1 bitmaps are store in VM heap memory but in native memory , which causes lot of problems in noticing leaks,for further info refer the video
Have a look at how WeakReference is used.

Categories

Resources