I'm writing a simple android application which is basically a modification of the fragments demo available in the android documentation. In the app, there is a file called Ipsum.java which has a static ArrayList of Strings called Headlines.
In the onCreate() method of the main activity, I have the following code which adds some elements into the array list.
if (savedInstanceState == null){
Ipsum.Headlines.add("String 1 ");
Ipsum.Headlines.add("String 2");
}
savedInstanceState is a Bundle that the system passes to the method, if the app is being resumed from some inactive state. The logic is that if savedInstanceState is null, then the app is not being resumed but being started as a new instance.
If I leave the app using the "Home" button and re-enter the app, the arrayList contains only the two elements: "String 1" and "String 2". (This is the desired behavior)
However, if I leave the app using the back button, and then re-enter the app, the "String 1" and "String 2" elements are added again. The array then has 4 elements.
String 1
String 2
String 1
String 2
(The contents of the arrayList can be seen because they are used to populate a listView) It seems that the app is storing the contents of the static array list when the back button is pressed.. and that a Bundle is not passed to the onCreate() method when the app is restarted. Can someone explain what's happening here, in terms of the app life cycle?
May This Help you:
Lets start with a bit of background: What happens when you start an application?
The OS starts a process and assigns it a unique process id and allocates a process table.A process start an instance of DVM(Dalvik VM); Each application runs inside a DVM.
A DVM manages class loading unloading, instance lifecycle, GC etc.
Lifetime of a static variable: A static variable comes into existence when a class is loaded by the JVM
and dies when the class is unloaded.
So if you create an android application and initialize a static variable, it will remain in the JVM until one of the following happens:
1. the class is unloaded
2. the JVM shuts down
3. the process dies
Note that the value of the static variable will persist when you switch to a different activity of another application and none of the above three happens. Should any of the above three happen the static will lose its value.
For More Detail: Read the Answer of Samuh in this Link... Click Here