onRestoreInstanceState not being called
Follow on from a previous question
One first screen activity I am clicking a button and doing this
Intent intent = new Intent(MainMenu.this, NewClass.class);
intent.putExtra("value1", value1);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Value is passed to new activity and is used in the onCreate()
-method
On new Activity I am saving the state when I click back button
@Override
protected void onSaveInstanceState(Bundle outState) {
// the UI component values are saved here.
super.onSaveInstanceState(outState);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG).show();
}
@Override
public void onBackPressed() {
//super.onBackPressed();
Intent intent = new Intent(RoundScoring.this, MainMenu.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
Toast.makeText(this, "Back Button Pressed", Toast.LENGTH_LONG).show();
}
On the first screen again I am clicking a different button with the following :
Intent intentContiune 开发者_JS百科= new Intent(MainMenu.this, NewClass.class);
intentContiune.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intentContiune);
The Activty is loaded but always fails as the value has not been set. I wrote a onRestorInstanceState
to re-populate the value from the bundle but it is never fired. Can someone say what I am doing wrong
Thanks for your time
UPDATE
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(DEBUG_TAG, "returnstate called");
super.onRestoreInstanceState(savedInstanceState);
value = savedInstanceState.getString("value");
}
Use Application
yourApplication.java
public yourApplication extends Application {
String Value;
public synchronized String getValue(){
return Value;
}
public synchronized void setValue(String Value){
this.Value = Value;
}
}
AndroidManifest.xml
<application android:name="yourApplication" ...
Now You can save value anywhere using:
SAVE
((yourApplication) getApplicationContext()).setValue("something");
LOAD
((yourApplication) getApplicationContext()).getValue();
The onRestoreInstanceState
get's called when activity reinitializes not after activity starts.....so on starting activity it will not be called ...
If you are saving some data then you can use sharedPreference for situation like this....
onRestoreInstanceState()
is very tricky. I suggest you to use SharedPreferences
http://developer.android.com/guide/topics/data/data-storage.html#pref
Check your
AndroidManifest.xml
It should not contain
android:configChanges="orientation|keyboardHidden"
The system calls onRestoreInstanceState only if there is a saved state to restore in your Activity. Precisely when the Activity has been killed by the system due to lack of resources it's used to preserve the state saved in onSaveInstanceState.
If you want to save some information and have them available at every moment then just use SharedPreferences.
精彩评论