Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android global variable

How can I create global variable keep remain values around the life cycle of the application regardless which activity running.

like image 398
d-man Avatar asked Dec 22 '09 07:12

d-man


2 Answers

You can extend the base android.app.Application class and add member variables like so:

public class MyApplication extends Application {      private String someVariable;      public String getSomeVariable() {         return someVariable;     }      public void setSomeVariable(String someVariable) {         this.someVariable = someVariable;     } } 

In your android manifest you must declare the class implementing android.app.Application (add the android:name=".MyApplication" attribute to the existing application tag):

<application    android:name=".MyApplication"    android:icon="@drawable/icon"    android:label="@string/app_name"> 

Then in your activities you can get and set the variable like so:

// set ((MyApplication) this.getApplication()).setSomeVariable("foo");  // get String s = ((MyApplication) this.getApplication()).getSomeVariable(); 
like image 72
Jeff Gilfelt Avatar answered Sep 29 '22 06:09

Jeff Gilfelt


You can use a Singleton Pattern like this:

package com.ramps;  public class MyProperties { private static MyProperties mInstance= null;  public int someValueIWantToKeep;  protected MyProperties(){}  public static synchronized MyProperties getInstance() {         if(null == mInstance){             mInstance = new MyProperties();         }         return mInstance;     } } 

In your application you can access your singleton in this way:

MyProperties.getInstance().someValueIWantToKeep 
like image 45
Ramps Avatar answered Sep 29 '22 08:09

Ramps