Tuesday 13 September 2011

Static variables in your Android Application

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.


<resources>
   <string name="version_name">2.0.0</string>
</resources

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();
...
 
Try this :)

No comments:

Post a Comment