Friday, August 12, 2011

Static variables in your Android Application

I've got recently problems in an android application with static variables, which were declared in some activities. After some time they seemed to be erased.

So I asked again people on StackOverflow and I've got a good solution for my problem.

Instead of declaring static variables in an activity you can also do it in your own subclass of the Activity class, which is a singleton.

Within strings.xml I have the application version.


2.0.0

I didn't want to store this value second time as a constant in my java code. And here is the solution.

public class MyApp extends Application
{
private static String appVersion = "";
public static void setAppVersion (String version)
{
appVersion = version;
}

public static String getAppVersion ()
{
return appVersion;
}
}

In my first activity I initialize version variables:
public void onCreate(Bundle savedInstanceState) 
{
...
String appVersion = this.getString(R.string.version_name);
MyApp.setAppVersion(appVersion);
...
}

Now version value can be read everywhere in your application also in normal java classes:

...
String version = MyApp.getEasyGOVersion();
...

It works fine for me and I hope, it will work for you as well.