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);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…