在android中的活动之间传递非原始类型的数据 [英] Passing data of a non-primitive type between activities in android

查看:19
本文介绍了在android中的活动之间传递非原始类型的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您要启动一个新活动并将当前活动的一些数据传递给它.如果数据是原始类型,您可以简单地使用意图并添加额外内容,但是对于更复杂的数据结构(如数组列表或对象),您将如何执行此操作?

Suppose you want to start a new activity and pass it some data from the current activity. If the data is of a primitive type you could simply use an intent and add extras, but how would you do this for more complex data structures like arraylists or objects?

推荐答案

您有几个选择:

  1. 您可以将更复杂的结构包装在一个实现 Parcelable 接口的类中,该接口可以存储在一个额外的
  2. 您可以将更复杂的结构包装在一个实现 Serializable 接口的类中,该接口可以存储在一个额外的
  3. 您使用静态数据成员来传递信息,因为它们都在同一个进程中
  4. 您使用外部存储(文件、数据库、SharedPreferences)
  5. 正如刚刚发布的人所指出的,使用通用组件,例如自定义Application 或本地Service
  1. You could wrap the more complex structure in a class that implements the Parcelable interface, which can be stored in an extra
  2. You could wrap the more complex structure in a class that implements the Serializable interface, which can be stored in an extra
  3. You use static data members to pass stuff around, since they are all in the same process
  4. You use external storage (file, database, SharedPreferences)
  5. As the person who just posted noted, use a common component, such as a custom Application or a local Service

您不想做的是通过附加功能传递大内容.例如,如果您正在创建一个从相机中抓取图片的应用程序,您不希望将它们传递给额外的东西——使用静态数据成员(听起来很糟糕).Intent 旨在跨进程工作,这意味着需要进行一定量的数据复制,当大数据不需要时,您希望避免这种情况.

What you do not want to do is pass big stuff via extras. For example, if you are creating an application that grabs pictures off the camera, you do not want to pass those in extras -- use a static data member (icky as that sounds). Intents are designed to work cross-process, which means there is some amount of data copying that goes on, which you want to avoid when it is not necessary for big stuff.

这篇关于在android中的活动之间传递非原始类型的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆