android - 如何通过 bundle 发送对象

标签 android serialization android-activity bundle parcelable

我需要通过一个包传递对完成我大部分处理的类的引用。

问题在于它与 Intent 或上下文无关,并且有大量的非原始对象。如何将类打包成可打包/可序列化并将其传递给 startActivityForResult

最佳答案

您还可以使用 Gson 将对象转换为 JSONObject 并将其传递给 bundle。对我来说,这是我发现的最优雅的方式。我还没有测试过它对性能的影响。

在初始 Activity 中

Intent activity = new Intent(MyActivity.this,NextActivity.class);
activity.putExtra("myObject", new Gson().toJson(myobject));
startActivity(activity);

在下一个 Activity 中

String jsonMyObject;
Bundle extras = getIntent().getExtras();
if (extras != null) {
   jsonMyObject = extras.getString("myObject");
}
MyObject myObject = new Gson().fromJson(jsonMyObject, MyObject.class);

关于android - 如何通过 bundle 发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4249897/

相关文章:

c# - 在存储到 Redis 之前是否使用 protobuf-net 序列化原语

java - 如果应用程序是多语言的,定位元素的最佳方法是什么?

android - Gradle和对Android Studio 3.0.1的依赖性错误

c++ - C++实现序列化的数据结构对齐

c - 串行通信重置/etc/profile (linux)

java - Android OOP 设计基础

Android - 对 FragmentActivity 的 fragment 的 Intent Activity

android - 获取 Android Activity 以运行非 Activity 代码

android - 如何正确清理 Android 监听器?

android - 通过市场强制更新应用程序,就像用户单击 "Update"