How do you pass an object array to an Activity?

只谈情不闲聊 提交于 2019-12-21 04:29:26

问题


I have read posts on passing arrays from and to activities, but I am confused as to how I would do it for my specific case.

I have an array of objects called DaysWeather (a DaysWeather[] array) where the objects have several String attributes as well as a bitmap attribute. I read somewhere that you have to make it serializable or parceable or something, but it seems messy at first glance.

Could someone lead me in the right direction?

Is there a simple way to do this?


回答1:


Your objects need to implement the Parcelable interface.

When this is done, you can create the Parcelable array and pass it to the activity:

// We assume we have an array: DaysWeather[] input;
Parcelable[] output = new Parcelable[input.length];
for (int i=input.length-1; i>=0; --i) {
    output[i] = input[i];
}

Intent i = new Intent(...);
i.putExtra("myArray", output);

Also note that when you implement the Parcelable interface, do not serialize full heavy objects. For instance, for your bitmap, serialize the ressource ID only and when inflating, recreate the bitmap from the ressource ID.



来源:https://stackoverflow.com/questions/4181885/how-do-you-pass-an-object-array-to-an-activity

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