Reputation: 14771
I am developing an Android app. I am testing using onSaveInstanceState event in activity. But it is not working as I expected, because value string is always empty when I retrieve it back onCreate event.
This is my activity
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("message","Hello world!");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null)
{
Toast.makeText(getBaseContext(),savedInstanceState.getString("message"),Toast.LENGTH_SHORT).show();
//Log.i("DATA_FROM_STATE",savedInstanceState.getString("message"));
}
}
When I run activity and change orientation, it is always toasting empty message. When I test uncommenting the Log line, it is giving me error because data string is empty or null. Why it is not working? How can I save and retrieve correctly?
Upvotes: 0
Views: 724
Reputation: 965
At first glance I saw that your are calling super before you saved the data And I guess your app is running on API21+ version of Android, because it is needed to call your method
public void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState);
@Override
public void onSaveInstanceState(Bundle outState,PersistableBundle outPersistentState) {
outState.putString("message","Hello world!");
super.onSaveInstanceState(outState, outPersistentState);
}
Upvotes: 0
Reputation: 143
Wrong method override. Should use onSaveInstanceState(Bundle outState) and it will work. You can copy below snippet and test it.
public class MainActivity extends AppCompatActivity {
private final String SAVED_MESSAGE_KEY = "SAVED_MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null) {
if(savedInstanceState.containsKey(SAVED_MESSAGE_KEY)) {
Log.i("Saved message is:", savedInstanceState.getString(SAVED_MESSAGE_KEY));
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVED_MESSAGE_KEY, "Hello world!");
}
}
Upvotes: 1