Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array of Address objects to an other Acitvity

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

like image 914
Flo Avatar asked Sep 05 '10 19:09

Flo


3 Answers

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);              
}
like image 91
LiorZ Avatar answered Nov 15 '22 06:11

LiorZ


or on java1.6:
    Parcelable[] x = bundle.getParcelableArray(KEY);
    addresses = Arrays.copyOf(x, x.length, Address[].class);
like image 38
user3746807 Avatar answered Nov 15 '22 04:11

user3746807


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;
}
like image 28
Brais Gabin Avatar answered Nov 15 '22 06:11

Brais Gabin