如何在 Bundle 中发送自定义对象的 ArrayList

编程入门 行业动态 更新时间:2024-10-25 18:26:54
本文介绍了如何在 Bundle 中发送自定义对象的 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个应用程序,它使用服务每 x 秒创建一个自定义对象 (MyObject) 的 ArrayList.然后我希望我的 Activity 获得这个 ArrayList.

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.

我目前计划让服务在每次完成数据查询时向活动的处理程序发送一条消息.我希望 Handler 的消息包含 MyObjects 的 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.

在 Activity 中构建方法以从消息中获取此 ArrayList 时,我注意到我不能.

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

如果我尝试过

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

然后我将它传递给预期的 ArrayList 的方法不会接受它.如果我尝试投射结果:

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")

我收到错误:Cannot cast from ArrayList到 ArrayList

MyObject 实现了 Parcelable,并且通过让我的活动调用服务上的方法来检索它,我已成功地将一个 ArrayList 从我的服务发送到我的活动.不过,我正在努力避免让我的活动轮询我的服务以获取这些数据.

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) 如何在消息中将包内的 ArrayList 发送给处理程序?

2) 是否应该使用不同的模型来让我的服务更新我的活动中可能可见或不可见的数据?我总是希望我的活动中的数据是来自服务的最新数据.

推荐答案

应该使用另一个模型.我问的另一个问题提供了答案:

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

如果活动正在运行,则禁止来自服务的通知

至于 #1,您可以通过从 ArrayList 声明中删除泛型并在需要时进行适当转换来解决它.我知道这行得通,因为这是我在根据提出的另一个问题重构之前所做的.

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.

这篇关于如何在 Bundle 中发送自定义对象的 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 09:50:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884918.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   对象   如何在   ArrayList   Bundle

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!