I have an application which has 3 activities.
- Activity1
- Activity2
- Activity3
When the user opens the application, I am fetching the user's location and storing it in a static variable in a Helper class. Lets say the variable is latlng. Now I need to access the value of latlng variable in Activity2. So i simply use Helper.latlng in Activity2 . It works fine most of the time.
But if I press the home button and open some other application, and then come back to my application, my application force closes. After debugging I find out that latlng variable is becoming null in Activity2.
So, after going through various documentations, I came to find out that if a lot of applications are running, then Android OS may kill some applications. So basically if I open some other application, my current activity is destroyed by the OS. So automatically all my static variables are gone.
One way to overcome this is continue using static variables with onSavedInstanceState method which is called when the activity is getting destroyed.
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
LatLng latLng = Helper.latlng;
outState.putParcelable("latlng",latLng);
}
And retrieve it using
if( savedInstanceState != null ) {
Helper.latlng = savedInstanceState.getParcelable("latlng");
}
I am really confused whether I should go with the above approach. Is there any other way to use a variable across different activities in Android. I can from my experience say that using static variables is not a safe bet.