Duk
Duk

Reputation: 143

onSaveInstanceState Not writing data

My application has two Activity's. I need an Activity to save a String, so for this I used the method below.

@Override
protected void onSaveInstanceState(Bundle bundle) {
  bundle.putString("ACTIVITY", "Dados que precisando ser salvos!");
  super.onSaveInstanceState(bundle);
}

When I go to the second activity the above method is called, it is a correct behavior in the application. But upon returning to my first activity, the bundle is null, and I'm not understanding why, can anyone help me?

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   if (savedInstanceState != null){
   String teste = savedInstanceState.getString("ACTIVITY");
   }
}

Upvotes: 0

Views: 67

Answers (2)

Sharath kumar
Sharath kumar

Reputation: 4132

You can use onSaveInstanceState() and onRestoreInstanceState() only when an activity is destroyed and recreated.

When an intent is called from say activity A to activity B, activity A is moved to back stack and not destroyed. Activity A onStop() is called and not onDestory(), so when you come back onRestart() is called and also the bundle doesn’t get saved.

Instead, you can use sharedPreferences in your activity A like this.

1.Save the value on click of button

SharedPreferences sharedPref = getSharedPreferences("YOUR PREF NAME", Context.MODE_PRIVATE);
sharedPref.edit().putString("ACTIVITY", "Dados que precisando ser salvos!").apply();

2.Restore the value from preferences on restring app

sharedPref.putString("ACTIVITY", null);

Edit:If your are not using activity use context to use preference

SharedPreferences sharedPref = context.getSharedPreferences("YOUR PREF NAME", Context.MODE_PRIVATE);

Upvotes: 0

Vishvendu Palawat
Vishvendu Palawat

Reputation: 576

Override

onRestoreInstanceState() where you want the values to be extracted :

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState. 
  // This bundle has also been passed to onCreate. 
  String myString = savedInstanceState.getString("ACTIVITY");
}

Best practice to use both method in the same activity to restore and then use that data to some other activity, for that you can use shared preference or pass intent.

Upvotes: 1

Related Questions