Reputation: 1086
i want to save the value of a textView when the App goes into onPause. so I implemented onSaveInstanceState and onRestoreInstanceState. but as shown below in the logcat output, onRestoreInstanceState is never called.
i know that both of onRestoreInstanceState and onSaveInstanceState are not part of the App lifecycle, so why onSaveInstanceState is getting called while onRestoreInstanceState is not? and how to call onRestoreInstanceState?
code:
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.w(TAG, LogAnd.i("onResume", ""));
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
tvStatus.setText("[" + SysUtils.getDeviceName() + "] no Bluetooth installed.");
} else {
tvStatus.setText("[" + SysUtils.getDeviceName() + "] Bluetooth installed.");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
Log.w(TAG, LogAnd.i("onSaveInstanceState", ""));
outState.putString("statusText", tvStatus.getText().toString());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Log.w(TAG, LogAnd.i("onRestoreInstanceState", ""));
String status = savedInstanceState.getString("statusText");
tvStatus.setText(status);
}
logcat:
08-23 18:36:31.544: W/MainActivity(32195): -> onResume:
08-23 18:36:31.904: W/MainActivity(32195): -> onPause:
08-23 18:36:32.694: W/MainActivity(32195): -> onSaveInstanceState:
08-23 18:36:34.014: W/MainActivity(32195): -> onResume:
08-23 18:36:42.904: W/MainActivity(32195): -> onPause:
08-23 18:36:43.784: W/MainActivity(32195): -> onSaveInstanceState:
08-23 18:36:43.784: W/MainActivity(32195): -> onStop:
08-23 18:36:50.084: W/MainActivity(32195): -> onStart:BT-Receiver Registered
08-23 18:36:50.084: W/MainActivity(32195): -> onResume:
Upvotes: 5
Views: 4216
Reputation: 12478
As the official reference says about onSaveInstanceState
:
This method is called before an activity may be killed
If there is possibility for an Activity
to be killed, onSaveInstanceState
will be called regardress of actually it will have been killed or not.
While onRestoreInstanceState
is called when actually the Activity
has been killed.
Therefore, if actually the Activity
has not been killed, onRestoreInstanceState
is not called.
Thus, asymmetry calling between onSaveInstanceState
and onRestoreInstanceState
can be happen. If you want to make sure to be called onRestoreInstanceState
, you should surely kill your Activity
.
Upvotes: 2
Reputation: 7060
onRestoreInstanceState()
is called only after onStart()
and so it is not called after onResume()
. Check this complete activity lifecycle.
I hope this helps!
Upvotes: 2