Search code examples
androidarraysandroid-intentextra

Integer[] not working in Intent#putExtra(...)


I want to put an int[] into an Android Intent. For various reasons I am getting a LinkedList<Integer>, so I tried (roughly) this:

LinkedList<Integer> myList = getIntegerList();
Intent intent = new Intent (context, class);
intent.putExtra("com.me.INTARRAY",  myList.toArray());

This didn't work because toArray() was giving me an Object[]. I thought I could fix it by doing

intent.putExtra("com.me.INTARRAY", (Integer[]) myList.toArray(new Integer[myList.size()]) )

which does indeed produce an Integer[]; however, getting it out of the Intent STILL doesn't work.

Ultimately this isn't too hard to work around with a for loop so I ask more for curiosity than any other reason, but ... how do you get an Integer[] into an Intent extra as though it were an int[]?


Solution

  • I have not tested this thoroughly, but I believe it should work. You can try it.

    Integer[] integerArray = {/*something */ };
    intent.putExtra("com.me.INTARRAY",  integerArray);
    

    And then (not working)

    Integer[] newArray = (Integer[]) getIntent().getSerializableExtra("com.me.INTARRAY");

    EDIT: Ahh.. After a little research and testing it seems the above is not possible. It is not possible because the compiler would have to iterate through every element to verify the cast. A solution(and I have testet it this time) would be to do this instead:

    Object[] s = (Object[]) getIntent().getSerializableExtra("com.me.INTARRAY");
    Integer[] newArray = Arrays.copyOf(s, s.length, Integer[].class);
    

    I found the explanation here: Deserializing Arrays on Android