declare global variable in android- example code

To declare global variable in android, you need to 
1) create your own subclass of android.app.Application
2) and then specify that class in the application tag in your manifest. 
Android will automatically create an instance of that class and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):
  • Sub Class of Application :
     public class MyApp extends Application {
           String foo;
      }
  • In the AndroidManifest.xml add android:name
 <application 
     android:icon="@drawable/icon" 
     android:label="@string/app_name" 
     android:name="com.company.MyApp">
  </application>

Full Example :
class MyApp extends Application {

  private String myState;

  public String getState(){
    return myState;
  }
  public void setState(String s){
    myState = s;
  }
}

class Blah extends Activity {

  @Override
  public void onCreate(Bundle b){
    ...
    MyApp appState = ((MyApp)getApplicationContext());
    String state = appState.getState();
    ...
  }
}

1 comment :

  1. Hi Ganesh

    useful post...

    thanks for sharing

    ReplyDelete

Your Comment and Question will help to make this blog better...