问题
I am trying to keep my HashMap values when I navigate to another activity and return. This is the code I have for now.
The HashMap works and is able to grab and save the data from the EditText in the view.
However as soon as I leave from the activity and return, the HashMap is reinitialized to empty -> {}
I have looked at documentation and it seems this is the correct way of ensuring that a variable data is persisted. However it does not work.
please let me know what could be the issue:
public class ScriptActivity extends MainActivity {
HashMap timeAndMessages;
EditText message;
EditText time;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_script);
if (savedInstanceState != null) {
timeAndMessages = (HashMap) savedInstanceState.getSerializable("alerts");
} else {
timeAndMessages = new HashMap();
}
message = (EditText)findViewById(R.id.messageText);
time = (EditText)findViewById(R.id.timeText);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
restore(savedInstanceState);
}
private void restore(Bundle savedInstanceState) {
if (savedInstanceState != null) {
timeAndMessages = (HashMap) savedInstanceState.getSerializable("alerts");
}
}
public void createMessage (View view){
String stringmessage = message.getText().toString();
int inttime = Integer.parseInt(time.getText().toString());
timeAndMessages.put(inttime, stringmessage);
Toast.makeText(getApplicationContext(), "Will display : " + stringmessage + " At time : " + Integer.toString(inttime) , Toast.LENGTH_LONG).show();
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putSerializable("alerts", timeAndMessages);
}
}
回答1:
However as soon as I leave from the activity and return, the HashMap is reinitialized to empty -> {}
If by "leave from the activity and return", you mean press the BACK button, then do something to start a fresh activity... then your behavior is expected.
The Bundle
for the saved instance state is used in two main scenarios:
- Configuration changes (e.g., user rotates the screen)
- Process termination, and the user returns to your recent task (e.g., via the overview screen)
Pressing BACK to destroy the activity is neither of those. Hence, the state is not saved.
If this HashMap
represents model data — the sort of data that you expect to be able to get back to, time and again, no matter how the user uses your app — save it to a database, SharedPreferences
, other sort of file, or "the cloud".
You can read more about these scenarios in the Activity documentation.
来源:https://stackoverflow.com/questions/36510107/android-hashmap-not-persisting-when-returning-to-activity