android – Store application global data-ThrowExceptions

Exception or error:

Hi
What is the best way to store global objects/instances through out the application ?

How to solve:

Here is the following code which I use to store String in Application Context.

I make the class GlobalVariable.java

import android.app.Application;

public class GlobalVariable extends Application 
{
      private String myState;

      public String getState()
      {
        return myState;
      }//End method

      public void setState(String s)
      {
        myState = s;
      }//End method
}//End Class

In .Manifest I add the following code

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

Where I want to set the value of string I use the following code

GlobalVariable appState = ((GlobalVariable)getApplicationContext());
appState.setState("Testing");

& where I want to Retrive the data I use

GlobalVariable appState = ((GlobalVariable)getApplicationContext());
appState.getState();

###

Extend the Application object and store the references to your global objects in it.

###

What about Singleton pattern?

Leave a Reply

Your email address will not be published. Required fields are marked *