23

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

Harikrishnan R
  • 1,444
  • 4
  • 16
  • 27

3 Answers3

28

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();
Siddiqui
  • 7,662
  • 17
  • 81
  • 129
  • what about an Object (say class A) – Harikrishnan R Apr 20 '11 at 16:12
  • please look my previous post http://stackoverflow.com/questions/5726095/store-objects-in-applicationcontext – Harikrishnan R Apr 20 '11 at 20:33
  • @Harikrishnan R, I have added object of class A using the same procedure. – Siddiqui Apr 21 '11 at 06:09
  • This will not work perfectly for ICS and above versions with developer setting set to keep single activity. It will work fine if you relaunch application from recent application list and data will be reset to default values if relaunched from applications. Is there any way to overcome this problem? – Android_IT Nov 02 '12 at 12:00
  • 6
    Storing data in the Application object will do more harm than good - when an app goes to the background and the system kills it to reclaim resources, after reopening it the Application object is recreated from scratch (not persisted). So myState will be null. – javaxian Jun 05 '14 at 16:58
  • For more information about javaxian's answer, read this http://www.developerphil.com/dont-store-data-in-the-application-object/ . At the end, it explains how to simulate the application is being killed – mrroboaat Jul 15 '14 at 19:50
1

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

Naresh
  • 1,336
  • 9
  • 14
1

What about Singleton pattern?

Olegas
  • 10,349
  • 8
  • 51
  • 72