I'm trying to pass an array of Address objects to another Activity through an Intent object.
As the Address class implements the Parcelable interface I try to do the following. I got a List Address object from a Geocoder object, which I convert into a array of Address objects. Then I put this array into the Intent and call the activity.
final Address[] addresses = addresseList.toArray(new Address[addresseList.size()]);
final Intent intent = new Intent(this, SelectAddress.class);
intent.putExtra(SelectAddress.INTENT_EXTRA_ADDRESSES, startAddresses);
startActivityForResult(intent, REQUEST_CODE_ACTIVITY_SELECT_ADDRESSES);
On the other activity I try to retrieve the Address[] from the Intent with the following piece of code. But the call of the last line ends with a ClassCastException Landroid.os.Parcelable
.
Bundle bundle = getIntent().getExtras();
Address[] addresses = (Address[]) bundle.getParcelableArray(INTENT_EXTRA_ADDRESSES);
What am I doing wrong? How do I have to retrieve the Address[].
The problem is the casting. try:
Bundle bundle = getIntent().getExtras();
Parcelable[] parcels = bundle.getParcelableArray(INTENT_EXTRA_ADDRESSES);
Address[] addresses = new Address[parcels.length];
for (Parcelable par : parcels){
addresses.add((Address) par);
}
or on java1.6: Parcelable[] x = bundle.getParcelableArray(KEY); addresses = Arrays.copyOf(x, x.length, Address[].class);
The @LiorZ answer is completely true. I just merged his answer and this other in this handy function.
@SuppressWarnings("unchecked")
private static <T extends Parcelable> T[] castParcelableArray(Class<T> clazz, Parcelable[] parcelableArray) {
final int length = parcelableArray.length;
final T[] array = (T[]) Array.newInstance(clazz, length);
for (int i = 0; i < length; i++) {
array[i] = (T) parcelableArray[i];
}
return array;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With