简体   繁体   中英

How to send an ArrayList of custom objects in a Bundle

I have an application that uses a service to create an ArrayList of custom objects (MyObject) every x seconds. I then want my Activity to obtain this ArrayList.

I'm currently planning on having the Service send a message to the Activity's handler every time it finishes the query for the data. I want the message to the Handler to contain the ArrayList of MyObjects.

When building the method in the Activity to get this ArrayList out of the message, I noticed that I couldn't.

If I tried

msg.getData().getParcelableArrayList("myObjects")

Then the method I was passing it to that expected an ArrayList wouldn't accept it. If I tried casting the results:

(ArrayList<MyObject>)msg.getData().getParcelableArrayList("myObjects")

I received the error: Cannot cast from ArrayList<Parcelable> to ArrayList<MyObject>

MyObject implements Parcelable and I have successfully sent an ArrayList from my service to my activity by having my activity call a method on the service to retrieve it. I'm trying to go away from having my activity poll my service for this data, though.

1) How can I send an ArrayList inside the bundle in a message to handler?

2) Is there a different model I should be using to have my service update the data in my Activity that may or may not be visible? I always want the data in my activity to be the latest from the Service.

I had the exact same question and while still hassling with the Parcelable , I found out that the static variables are not such a bad idea for the task.

You can simply create a static field

public static ArrayList<MyObject> myObjects = .. 

and use it from elsewhere via MyRefActivity.myObjects

I was not sure about what public static variables imply in the context of an application with activities. If you also have doubts about either this or on performance aspects of this approach, refer to:

Cheers.

如果演员阵容是问题所在,只要留下它,不要施放它,错误就会消失。

There is another model that should be used. Another question I asked provided the answer:

Suppress notifications from a service if activity is running

As for #1, you could get around it by just removing the generics from the ArrayList declarations and casting as appropriate where needed. I know this works because that's what I did before refactoring based on the other question asked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM