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

戏子无情 提交于 2019-12-10 14:18:41

问题


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


来源:https://stackoverflow.com/questions/3647432/how-to-pass-an-array-of-address-objects-to-an-other-acitvity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!