I'm a beginner in Android and trying to restore the instance state when changing the orientation.
When I implement the restoration in onRestoreInstanceState()
method, it works. But when implemented inside onCreate()
method, it doesn't, as if no restoration is implemented, the EditText
view appears empty.
The problem is, it seems that the test in savedInstanceState != null
is not passing.
Here's the code in case of implementation is in onCreate()
:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null) {
EditText editText = (EditText) findViewById(R.id.edit_message);
editText.setText(savedInstanceState.getString("test_msg"));
}
}
// This method works as expected.
// public void onRestoreInstanceState(Bundle savedInstanceState) {
// EditText editText = (EditText) findViewById(R.id.edit_message);
// editText.setText(savedInstanceState.getString("test_msg"));
// }
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("test_msg", "this is test message");
super.onSaveInstanceState(savedInstanceState);
}
Have a look at Activity Lifecycle it might help you with your question.
In your code what seems to be wrong with it is that you only call super.onSaveInstanceState(savedInstanceState) after you put something in the Bundle, try first calling this method and then adding to the Bundle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.