Frank Zappa Frank Zappa - 1 year ago 143
Android Question

android onSavedInstanceState saving and restoring time

A - What is the proper way to save a date/time for screen rotation

B - Why does my implementation below add 20 seconds to the saved time?

I am processing some calculations over time. I track the beginning of a specified period (abegtim date) and the end of a specified period (aendtim date). Each time I receive a new GPS reading from a GPS related service, aendtim is updated. I cannot allow screen rotation to reset my abegtim but that is what is happening. (string2date is my function)

I tested the code below on rotation and abegtim comes out of onRestoreInstanceState with a new time that is 20 seconds later than when it goes in to onSavedInstanceState .

public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putString("abegtim", date2string("yyyy-MM-dd HH:mm:ss",abegtim));
Log.e("savedinst B4 abegtim " + abegtim," ");

public void onRestoreInstanceState(Bundle savedInstanceState){
String strabegtim = " ";
strabegtim = savedInstanceState.getString("abegtim", strabegtim);
abegtim = string2date("yyyy-MM-dd HH:mm:ss",strabegtim);
Log.e("savedinst AFTR abegtim " + abegtim," ");

E/savedinst B4 abegtim Tue Nov 22 08:20:16 PST 2016:

E/savedinst AFTR abegtim Tue Nov 22 08:20:36 PST 2016:

Answer Source

not sure why this happens, but converting to a string sounds like overcomplicating the problem.

You can use the timestamp value of the Date object instead.

Assuming abegtim is of type Date:

long timestamp = abegtim.getTime();


abegtim = new Date(timestamp);

Also make sure that you don't override the value set by onRestoreInstanceState to abegtim with the default value (of now) in a later callback. i.e., if you set the value of abegtim in your onCreate callback, make sure you only set it if savedInstanceState is null:

void onCreate(Bundle savedInstanceState) {
  if (savedInstanceState == null) {
    abegtim = new Date();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download