将带有对象的 ArrayList 传递给新的 Activity?
我正在尝试将 ArrayList 从第一个 Activity 传递到下一个 Activity。基本上,第一个活动解析 XML 文件并创建一个内部包含对象的 ArrayList。我想要做的是将 ArrayList 发送到我的第二个活动,并在 ListView 中显示一些对象数据。
我想带着意图这样做,但看起来通常只有原始数据类型通过意图传递。这是对的吗?
如果是这样,传递数据的更好解决方案是什么?当然,Android 必须提供一些东西才能完成这种事情。
非常感谢任何帮助/代码示例。
谢谢
编辑:
我通过首先创建和调用意图,然后仅解析我调用的 Activity 中的 XML 来解决这个问题。这样我就不再需要传递对象了。但对于那些感兴趣的人,您可以在此处了解如何通过活动传递数据。
I'm trying to pass an ArrayList from my first Activity to the next one. Basically, the first activity parses an XML file and creates an ArrayList with objects inside. What I want to do is send that ArrayList to my second activity and show some of the object data in a ListView.
I thought of doing this with an intent, but it looks like only primitive datatypes are usually passed through intents. Is this right?
If so, what would be a better solution to pass the data? Certainly Android must provide something to be able to do this kind of thing.
Any help/code examples are really appreciated..
Thanks
EDIT:
I solved this by first creating and calling the intent, and only parsing the XML in the Activity that I called. This way I didn't need to pass the objects anymore. But for those interested, you can read about how to pass data through activities, here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
复杂类型可以通过 Parcelable 的方式传递。这个问题就是一个例子:
帮助传递ArrayList和parcelable Activity
Complex types may be passed by means of Parcelable. An example is in this question:
Help with passing ArrayList and parcelable Activity
我会在数组上执行一个 toString 操作,并通过执行
intent.putExtra("label".array.toString());
将其作为额外参数传递,然后在新活动中恢复它。I would do a toString on the array and pass it as an extra by doing a
intent.putExtra("label". array.toString());
and then just recover it in the new activity.如果字符串列表是字符串,则可以使用 putStringArrayListExtra(String name, ArrayListvalue) 传递字符串列表。或者,您可以序列化 List,然后使用 putExtra(String name, Serialized value)。
如果您不想/不能使用上述内容,您可以使用带有对列表的静态引用的中央实用程序类。只需在第一个 Activity 中设置它并在第二个 Activity 中获取它即可。
You can pass a String List using
putStringArrayListExtra(String name, ArrayList<String> value)
if it is strings. Or, you could serialize List and then useputExtra(String name, Serializable value)
.If you don't want to/can't use the above, you could use a central util class with a static reference to the List. Just set it in your first Activity and get it in the second.
这可能是完全不好的做法,我也不知道更好,但您可以将 ArrayList 声明为公共和静态。然后只需使用 Activity.ArraylistName 访问它即可。
This could be totally bad practice and I wouldn't know any better, but you could declare the ArrayList as public and static. Then just access it with Activity.ArraylistName.
您可以在应用程序级别设置 ArrayList 的范围,也可以使用 Parcelable 来完成此操作。
You can set the scope of ArrayList at application level or you can do this using parcelable.
我用这个技巧从第一个活动发送到第二个活动。
第一个活动
第二个活动
检索
I made this trick to send from first Activity to second.
The first activity
The second activity
To retrieve