2

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");

}
avafab
  • 1,601
  • 3
  • 20
  • 38
  • Also make sure that you are not re-creating the `ArrayList` everytime. That is, you should not create a `new ArrayList` on orientation change – Kedar Paranjape Feb 09 '14 at 12:20
  • I create it before onCreated method (just after imports) – avafab Feb 09 '14 at 12:29
  • Also, as a side note, making your objects `Parcelable` is faster than Serialization on Android. See http://stackoverflow.com/questions/3611843/is-using-serializable-in-android-bad – Kedar Paranjape Feb 09 '14 at 12:55
  • I don't know the difference but I will try. I don't understand why the list is deleted, do I need to define an external variable, a database or a static? – avafab Feb 09 '14 at 13:56

2 Answers2

2

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"));
eugeneek
  • 812
  • 9
  • 24
  • This completely compiler error and the Android studio says "required `long[]` but found `java.lang.Long[]`" – ygngy Apr 18 '18 at 12:16
-1

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"
avafab
  • 1,601
  • 3
  • 20
  • 38
  • 1
    This is not a solution - its a workaround at best. Learn the reasons why android defaults to re-creating your activity on orientation change. Understand that your activity can be destroyed and recreated at any time regardless of orientation. Armed with this knowledge you will be better equipped to understand and solve your problem. – Greg Ennis Dec 30 '14 at 00:53