Reputation: 1360
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.
Upvotes: 3
Views: 7377
Reputation: 7248
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.
Upvotes: 1
Reputation: 12749
If the cast is the problem, just leave it be, dont cast it, the error will go away.
Upvotes: 0
Reputation: 1360
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.
Upvotes: 0