i have an Android application in which i use a class to store static data among activities, something like:
class Global
{
private static boolean mInitialized = false;
private static String mData = null;
public static void init()
{
mData = "something";
mInitialized = true;
}
public static boolean isInitialized()
{
return mInitialized;
}
public static String getData()
{
return mData;
}
}
So in the main activity onCreate i do:
if( Global.isInitialized() == false )
Global.init();
And then starts other activities, the action flow is:
MainActivity -> ActionActivity -> PluginActivity
Where Main is where i init the Global class, and Action & Plugin is where i use the getData() method of that class.
Now in some cases, i get really strange behaviour … if something unepected happens in PluginActivity ( NullPointerException for instance ), the activity crashes and the application goes back to the ActionActivity which launched it, but, at this point, during the onCreate of the ActionActivity ( where the Global class is supposed to be initialized ) i get an exception because the getData() returns null ( and isInitialized() is false ) as the Global class was never initialized by the MainActivity.
So, can an object with static members like my Global class be deallocated/cleared/whatever if something like an unexpected exception occurs ?
In general, activities should be independent of each other. You should not depend on them being launched in any particular order, or at all.
Instead, if you need to share global state data between activities, i.e. not just parameter passing in intent extras or results via
onActivityResult(), subclassApplication, put the init code in itsonCreate()and access it from activities usinggetApplication(). Also remember to declare the application class in your manifest. The system takes care that the application object is there when any of your activities are running.