What is the efficient way for saving/loading Bitmaps - android

I'm working on an app that can be used for taking notes, simply a drawing application which is keeping bunch of Bitmap objects. I completed creating those pages(Bitmap) and drawing part but i have trouble with memory management, i dynamically create Bitmap object as full screen (for ex; 1280x720) resolution then working on it.
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
When user starts to create new pages, normally memory keeps growing. Some point i'm getting "Out of memory" error then my application is crashing.
In my application user can navigate between pages with scrolling and can see maximum two pages at a time (partial pages). I wonder if there any existing API for saving those Bitmap objects which is not displayed at that moment and unload from memory and loading those Bitmap objects when need to display. If there is no existing API can you give me some ideas how can i write my own Memory manager, how i must save those Bitmaps and where ?
For example ; User start to create new pages 1-2-3-4 right now i just need show page4 on the screen i don't need to keep page1-2 (page3 could be in memory for smooth transition ?) in memory i need to save it to disk (or encode as PNG ? or any better solution ? ) When user start to scrolling up that means i need to show page3-page4 at the same time (Maybe i also need to load page2 at this moment to Memory for smooth scrolling), so my app works as like that.

You should use multi threading methods and associate them with async task. Take a look here https://developer.android.com/training/multiple-threads/run-code.html

Related

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.

Asynchronous bitmap buffering with GridView in Android

I am bulding up a grid of images for an app I'm building. It works like so:
Build up a list of Image IDs, which I must query using a different content provider each (these are images from MMS threads)
Create new activity, which hosts an ImageGridFragment. This fragment has a custom adapter that takes the grid of images, and loads each one as a bitmap asynchronously.
After images are loaded, they are cached in an LRU cache so I don't need to run unnecessary computation
So far, everything works quite well. However, I would like to pre-buffer images so that when the user scrolls down, s/he doesn't have to wait for images to load. They should already be loaded. The stock Android Gallery accomplishes. I've had a look at the source, but think there must be a more straightforward way.
To answer members' questions
Images are loaded one by one using the content://mms/part/xxx, where xxx is the ID of an image. These are MMS images, and to my knowledge, cannot be loaded as a batch process (though, maybe I'm wrong). I use a content provider in an AsyncTask to load each image
I've tried the following:
Pre buffer 30 images or so right when the fragment is created. This is not ideal because the massive I/O request, actually prevents the on-screen images from loading quickly (but the buffering does work well!)
Detect when the requested view to load is at the very bottom-right hand corner of the screen, which could work, but then would fail in the case that the GridView takes up only part of the screen. It also seems like there should be a cleaner way to do this
Thought about, but did not try, an OnScrollListener, but this will not pre-buffer images until I start scrolling, which is not ideal
So, my questions are:
Is there a good way to detect when the last GridView item is requested to load? I found that the GridView.getlastvisibleposition() method is not useful here, because it is actually returning the last element for which Adapter.getView() has been called for. If I can do this accurately, I can launch the buffer request at that time
Is there a better way to do this?
you can do right this
if(GridView.getlastvisibleposition() = mAdapter.count()-1)
how you load the images?
is it from URL or from sdcard?
are you using a image loader library?

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.

Trying to display a large image as tiles without hiccups

My tablet app has to display a very large image (2500x6000) and allow the user to pan across, zoom in & out. Since it can't fit into memory I've broken it into tiles and am loading those as needed. The problem I'm running into is that whenever I unload or replace a bitmap I cause garbage collection which pauses my app with noticeable stutter. I was wondering if anyone had come up with any clever ways to work around this? I create my bitmaps using BitmapFactory.decodeResource. I've tried replacing the same bitmap but garbage collection still runs (assuming it dumps the old bitmap and replaces it with a new one).
Thanks!
Figured out the answer! In API11+ BitmapFactory.Options has an attribute called inBitmap which will reuse the bitmap when loading content. I've implemented it as such:
mBg[i] = Bitmap.createBitmap(800, 1232, Bitmap.Config.RGB_565);
mBgOptions[i] = new BitmapFactory.Options();
mBgOptions[i].inBitmap = mBg[i];
mBgOptions[i].inPreferredConfig = Bitmap.Config.RGB_565;
mBgOptions[i].inMutable = true;
mBgOptions[i].inSampleSize = 1;
The garbage collector no longer runs and the pauses have been removed.
As an f.y.i, inSampleSize has to be set or it won't work.
If you are targeting Android 3.0 then this answer may help:
How to load tiles from a large bitmap in Android?
Pre-Android 3.0 you could build an HTML page of your tiled images and let the built-in browser handle the load and unload of the images. My answer here has some more details:
How to tile and scroll a large image (10000x10000) in android
Anyone else have any alternative approaches?
Are you using android:largeHeap="true"? That might reduce the frequency of GCs. Also given you are targeting tablets, then you can safely assume that you are dealing with a concurrent garbage collector. So it will work best if it has more, smaller chunks of memory to collect, i.e. smaller tiles.
I used this easy to integerate source of WorldMap application:
https://github.com/johnnylambada/WorldMap
This uses a huge image of a world map, and uses cache to display a map.
To integerate, I just copied all the java files (5 i guess) and used the surfaceView in my layout file. Then I went through the small OnCreate() method of ImageViewerActivity.java and used the code in my activity (with sligh alteration, depending on my personal use).

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