How to pass an array of Address objects to an othe

2019-06-23 11:39发布

问题:

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[].

回答1:

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


回答2:

or on java1.6:
    Parcelable[] x = bundle.getParcelableArray(KEY);
    addresses = Arrays.copyOf(x, x.length, Address[].class);


回答3:

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;
}