在android中的活动之间传递非原始类型的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1441871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing data of a non-primitive type between activities in android
提问by aspartame
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?
假设您要启动一个新活动并将当前活动的一些数据传递给它。如果数据是原始类型,您可以简单地使用意图并添加额外内容,但是对于更复杂的数据结构(如数组列表或对象),您将如何执行此操作?
回答by CommonsWare
You have a few options:
您有几个选择:
- You could wrap the more complex structure in a class that implements the
Parcelable
interface, which can be stored in an extra - You could wrap the more complex structure in a class that implements the
Serializable
interface, which can be stored in an extra - You use static data members to pass stuff around, since they are all in the same process
- You use external storage (file, database,
SharedPreferences
) - As the person who just posted noted, use a common component, such as a custom
Application
or a localService
- 您可以将更复杂的结构包装在一个实现
Parcelable
接口的类中,该类可以存储在一个额外的 - 您可以将更复杂的结构包装在一个实现
Serializable
接口的类中,该类可以存储在一个额外的 - 您使用静态数据成员来传递东西,因为它们都在同一个进程中
- 您使用外部存储(文件、数据库、
SharedPreferences
) - 正如刚刚发布的人所指出的,使用通用组件,例如自定义
Application
或本地Service
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.
你不想做的是通过额外的东西传递大东西。例如,如果您正在创建一个从相机中抓取图片的应用程序,您不希望将它们传递给额外的东西——使用静态数据成员(听起来很糟糕)。Intent 被设计为跨进程工作,这意味着有一定数量的数据复制在进行,当不需要大数据时,您希望避免这种情况。
回答by j pimmel
One option I am aware of is storing the data you are using in an Application object which all your activities can retrieve from context.
我知道的一种选择是将您正在使用的数据存储在 Application 对象中,您的所有活动都可以从上下文中检索该对象。
I have also heard of using Google Protocol Bufferto achieve a higher performing solution
我也听说过使用Google Protocol Buffer来实现更高性能的解决方案