Database reference or recreation? - android

I have a quick performance question: Is it quicker and efficient on memory to use a static singleton database reference or reopen it every time you need to access something?
Thanks for any help,
~Aedon

In Android the databases aren't kept in memory so keeping the reference will be light on your memory, but will use some file locks. Using a singleton would be my first choice, however, if you're using it in a service or a single activity, it doesn't necessarily need to be static.
If you're database instance keeps a reference to a Context, then by all means avoid making it static because it will be a good source of memory leaks.

Related

Is it healthy to continually call on resources(R) in Android?

I have an application that requires data from a list in more than one classes extending Context. Sometimes I can pass the reference of the list to these classes and sometimes I cannot. So, I was wondering if putting the list to R.array.mylist and then continually calling from them in different classes might be a better idea? I specifically want to know if there is "high/low/acceptable"(in terms of memory & CPU) overhead to calling Resources continually.
Any suggestions/answers is appreciated. Thank you.
The "R" (resources) file is a static reference to XML defined objects. Creating a reference in XML allows you to reference those objects using objects that extend Context. It uses the Resources class to reference these objects.
If you inspect the source code (http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/content/res/Resources.java#Resources) you will see it is essentially a handler for these XML defined classes. If you have access to Context then there are few steps you can take to improve upon a the short reference path that Context and Resources provide.
You can build your own mechanism for storing and/or referencing this array or you can use the one provided for you by the framework. Most likely you will find that the framework offers acceptable performance in terms of speed, memory allocation, etc. Since Context and Resources are loaded with your Application object, there is little overhead involved in using these tools. You will notice the source code attempts to optimize caching of XML objects, etc. That means the accessing and caching mechanism may not be optimized for some use-cases.
You may have situations where you can beat the effectiveness of the framework, but for most situations it is just fine. If you have a special use-case (like an array of 100,000 elements) then you might be able to optimize better than the framework. Most likely you will find that it is both convenient and effective to store your array as an XML defined object.

How does using singleton patterns in Android impact memory usage?

I'm thinking about using singleton patterns for adapters and helpers in an Android app that I'm building, but I'm not too familiar with Java's garbage collecting and how static attributes (eg static FooBar instance) impact memory usage.
Will it have a big enough impact in Android apps that I should avoid using it?
Depends on what you mean by "impact memory usage". An object isn't larger or smaller just because there is one instance of it enforced by a singleton pattern. In that sense there's no difference.
If it means you definitely have at most one copy of an object in memory instead of several, yes it could help.
Usually what people mean though, is, how long does the singleton live? does it stick around taking up memory when the app is in the background?
A static member is attached to an instance of its Class which is in turn attached to its ClassLoader. So the singleton lives as long as the ClassLoader. It turns out in Android that the app's ClassLoader goes away in onDestroy, not onPause, so a singleton implies you hold on to the memory even when the app is in the background.
As others have said, it depends. The case where it could be bad is if the singleton is holding references to objects that could otherwise be garbage collected. If there are a lot of references in the object, or references to large objects, you could be using memory you don't need. You could work around it by using weak references, but then you have to have code to recreate the objects when needed if they get garbage collected. You could not use the singleton pattern, which would allow things to get garbage collected (at least potentially), but at the expense of creating and throwing away objects. The best solution depends on the details of the object and its usage. One thing to always avoid is holding on to a reference to a UI object, such as a View.

What can I do to avoid memory leaks in my Android app?

My android app is taking more and more memory over time. I took a heap dump and analyzed it with MAT.
Here's the main leak suspect :
So it seems like one of my activities isn't cleared from memory after I quit the app (with back button) then when I restart the app a new instance is created and fills in the memory.
Now if they're PhantomReferences why the memory isn't cleared after a while or when I quit the app? The memory is never cleared even when I use other app etc. The only way to completely close the app is to use a task manager to manually kill the app.
What can I do to avoid this anarchic memory consumption ?
EDIT:
I found the problem!
Each activity was setting up a CustomExceptionHandler with Thread.setDefaultUncaughtExceptionHandler() and that CustomExceptionHandler was keeping a reference to the context. So I got rid of the context reference and I 'nulled' the DefaultUncaughtExceptionHandler in the onDestroy() method. That's really better now!
I would use the dominator tree functionality of MAT to find out what is above those references, this may give you an idea of which Activity is the culprit.
Make sure you haven't passed a Context anywhere and held a reference to it, this is a classic android memory leak and it's really easy to do!
Although some static analysis tools frown on this, in the onDestroy() methods of your Activity you can null all your local variables (except primitives), it helps to nudge the garbage collector sometimes and can make for an easier to analyse heap dump in MAT.
Some generic approaches to reduce size of the app what I generally follow is this :
Call finish() below passing an Intent to next activity, this will avoid piling up of stack and helps in gc(garbage collection)
If you are not using shared preferences to save data, flush them at exit by calling System.exit()
If you find any drawable images/layout xmls/java classes which you are not using in your final program, ensure you remove them from the project
Images have to be .png since JPEG images take lot of memory.
In case of using database(sqlite, internal database etc), a better approach would be using "try/catch/finally" blocks, In try you open the db, in finally you close it, which will avoid memory leaks caused because of not closing cursors or databases.
Use AsyncTask instead of threads. in onPostExecute()function, close the progress dialogs if any.

How to manage memory/cache from code?

My app is crashing after longer use - runs out of memory.
I am closing all activities after switching to next one, but I still have that problem.
Is it possible to programmatically clear cache / memory, so application does not run out resources?
Can I use getCacheDir() to accomplish that?
Apparently your app is leaking memory. Make sure you clean up unused resources, close databases, reuse variables, etc.
Also refer to this post on how to track down memory leaks and how to avoid them.

Using Application class for storing persistent data in Android

I find myself using the Application class a lot to persist user data. These are application wide resources, though I cheat by storing an integer or two sometimes. Are there any drawbacks of doing this? I could not find any documentation which puts a limit on the amount of data that can be stored here.
Well, the documentation to Application says :
There is normally no need to subclass
Application. In most situation, static
singletons can provide the same
functionality in a more modular way.
Also the stuff you put in there goes to the heap(*), which is size constrained (e.g. to 24 MB). If you want to store more data, you should put it in a database or on file system.
*) Technically Android's Dalvik vm may not have a heap, but other ways to store stuff in main memory.

Categories

Resources