0

I have an ArrayList<Long> object that i would like to retain on orientation change of my fragment. But the Bundle class does not have a putLongArrayList() method. I do see putParcelableArrayList(), putIntegerArrayList() and putStringArrayList().

Is there any reason why the Long version of the method is not defined? Is there a simple workaround for this other than creating wrapper parcelable class for the Long objects and then using putParcelableArrayList()?

faizal
  • 3,497
  • 7
  • 37
  • 62

1 Answers1

1

I think this is the method you should use for that

enter image description here

You will have to convert the ArrayList to an Array before you're able to put it in the Bundle, though.

When you get the LongArray from the Bundle, you can convert it back to an ArrayList so you can perform list like operations on it again.

Putting in Bundle

long[] array = new long[yourArrayList.size()];
for(int i=0;i<yourArrayList.size();i++){
    array[i] = yourArrayList.get(i);
}
Bundle b = new Bundle();
b.putLongArray("longs", array);

Getting from Bundle

long[] array = b.getLongArray("longs");
for(int i=0; i<array.length;i++) arrayList.add(array[i])
faizal
  • 3,497
  • 7
  • 37
  • 62
Tim
  • 41,901
  • 18
  • 127
  • 145
  • But the size of my array is undefined, that's why i used arraylist. I would have to convert it back after orientation change as well. Do you think there is an alternative? – faizal Nov 03 '14 at 10:48
  • You can use the ArrayList for all the normal operations, but when you are about to put it into the Bundle, you have to convert it to an Array first, and when you get it from the Bundle you can convert it back to an ArrayList – Tim Nov 03 '14 at 10:50
  • `yourArrayList.toArray(new long[yourArrayList.size()])` does not work because it oly allows me to use `new Long` not `new long` – faizal Nov 03 '14 at 10:59
  • Use new Long then ;-) – Tim Nov 03 '14 at 11:01
  • but `putLongArray()` only accepts `long[]`, not `Long[]` :) – faizal Nov 03 '14 at 11:21
  • And `Arrays.asList()` returns a list of an array, that can no longer be expanded. That defeats the purpose of having an `ArrayList`. – faizal Nov 03 '14 at 11:28
  • 1
    A workaround would be to create a new ArrayList and loop over the Array, filling the ArrayList with the Array's values. – Tim Nov 03 '14 at 12:07
  • @faizal did you get it to work? I approved your edit – Tim Nov 03 '14 at 14:30
  • thanks that's what i ended up doing. I have edited your answer with the required code changes. Will accept it once it is accepted by peer review. – faizal Nov 03 '14 at 14:30