avafab
avafab

Reputation: 1701

Android save and restore ArrayList <Long> while screen changes

I have lists of times that I take with a timer, if I rotate the screen they are deleted. I tried following code, but it crashes. I think there is a problem in the saving/restoring format.

ArrayList<Long> timesList = new ArrayList<Long>(); // List of partial times in milliseconds

/** Save state while screen orientation changes */

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.    

  savedInstanceState.putSerializable("PartialTimes", timesList);

}


/** Restore state while screen orientation changes */

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.

  timesList = (ArrayList<Long>) savedInstanceState.getSerializable("PartialTimes");

}

Upvotes: 2

Views: 2802

Answers (2)

eugeneek
eugeneek

Reputation: 1430

Just use for save

Long[] array = new Long[list.size()];
array = list.toArray(array);
savedInstanceState.putLongArray("PartialTimes", array);

And for retrive

ArrayList<Long> list = Arrays.asList(savedInstanceState.getLongArray("PartialTimes"));

Upvotes: 2

avafab
avafab

Reputation: 1701

I finally solved the problem by putting this line in the manifest, inside main activity, in this way it keeps the list values even if the orientation changes.

android:configChanges="keyboardHidden|orientation"

Upvotes: -1

Related Questions