1

I would like to preserve the data or string on reload of the activity without using shared prefrences or sqllite databases.

Currently I have tried OnsavedInstancestate or OnRestoreInstancestate method but it will work only if orientation changes not for reloading the activity...

Please suggest me to overcome this.

Regards priya

3 Answers3

1

You can use singleTon class mechanism here.

  • Try to create a singleton class in your app.
  • Get instance of the class in your activity.
  • set the data to the class in onCreate()
  • get the data from the class whenever you want say in onRestart().

To learn more about singleTon class see this..

Create singleton class

public class Singleton {

    private static Singleton singleton = new Singleton();

    /*
     * A private Constructor prevents any other class from instantiating.
     */

    public String valueToStore;

    private Singleton() {
    }

    /* Static 'instance' method */
    public static Singleton getInstance() {
        return singleton;
    }

    public String getValueToStore() {
        return valueToStore;
    }

    public void setValueToStore(String valueToStore) {
        this.valueToStore = valueToStore;
    }

}

In your activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Singleton singleton = Singleton.getInstance();

    singleton.setValueToStore("Hai");
}



@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    super.onRestart();

    Singleton singleton = Singleton.getInstance();

    Log.d("Value", singleton.getValueToStore());
}
Naveen
  • 1,948
  • 4
  • 17
  • 21
1

You could try using the application class to store the data in a global singleton that would persist the data, then you could load and store the data from the singleton when you needed it using getter and setter methods.

See this similar question for how to do it: Using the Android Application class to persist data

Community
  • 1
  • 1
Patimo
  • 128
  • 1
  • 9
0

The easiest way to keep data when an activity is destroyed is to use

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("Test", "Test");
    super.onSaveInstanceState(outState);
}

Note that this will not get called when the user press the back button only when the system destroys the activity or another activity comes above.

Decoy
  • 1,598
  • 12
  • 19