private static final String KEY = "qaz";
private String aString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.txt);
final String saved;
if (savedInstanceState != null) {
saved = savedInstanceState.getString(KEY);
report("[" + saved + "]");
} else {
saved = null;
report("[NULL]");
}
if (aString==null && saved!=null) {
aString = saved;
report("A");
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
report("s");
savedInstanceState.putString(KEY, aString);
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onPause() {
report("p");
super.onPause();
}
@Override
public void onBackPressed() {
report("b");
super.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void report(String s) {
aString += " " + s;
Log.v("report", aString);
textView.setText(aString);
}
private static final String KEY = qaz; private String aString; @Override public void onCreate(Bundle
Share
onSaveInstance is intended to persist a value from one instance of your activity to the next, for example when the activity is destroyed and recreated on an orientation change. Just remember that when your activity is recreated, it is an entirely new instance of the class you’ve defined to extend the Activity class and therefore, all local fields (variables) will be re-initialised.
As you’ve already discovered, SharedPreferences are a good way to persist a value beyond the Activity lifecycle and of course, there are others. The values saved in onSaveInstance and retrieved in onCreate are intended for you to be able to initialise a new instance of your activity to the same state it was before it was destroyed.
Imagine for example that you have a messaging application and your user has already entered several lines of text. They then accidentally flip the orientation (we’ve all done that right?) then flip it back. How frustrated would they be to see that their text had disappeared?! So a good developer would save the current content of the TextView in onSaveInstance and retrieve it in onCreate. If any value is retrieved, it is passed to the setText() method so that the user can continue from where they were.
Take a look here. Learning the Activity life cycle, how to control it and how to pass values between Activities (either 2 different Activities or 2 instances of the same Activity) is one of the keys to unlocking the Android kingdom.
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
The key point is to understand when each callback is called and, even more importantly, what may or may not be called by Android. For example, when your app is in the background,there are NO guarantees that your activity will be called again if Android decides to kill your app.
Good luck.