在 Android 中传递大型复杂对象



我正在编写一个有趣的项目,该项目需要自定义对象中的自定义对象(例如:All_Animals,All_Dogs,All_Labs,My_Lab类型的东西(。问题是我需要将一个对象从一个活动传递到另一个活动,但该对象具有其他自定义对象的 ArrayLists 作为变量。我显然可以将所有内容转换为字符串并使用 putExtra(( 传递它,但这需要大量额外的代码,并且保持持久和有条理会变得棘手。

无论如何,我的问题是,在java(特别是在android中(中,将带有ArrayLists的复杂自定义对象作为变量从一个活动传递到另一个活动的最佳方法是什么?

将大数据(包括base64图像(传递到Intent中可能是旧手机(如三星S4 Mini(的问题。

在这种情况下,我更喜欢数据库。如果不想使用数据库,可以使用Parcelable序列化对象并保存它。

另一种方法是,使用 Gson 库序列化对象并将其保存到SharedPreferences中。然后在第二个活动中仅通过密钥接收它。

//first activity
List<A lot of objects> list;
String jsonList = new Gson().toJson(list);
SharedPreferences preferences = context.getPreferences(Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("UNIQUE_LIST_KEY",jsonList);
editor.commit();
Intent intent = new Intent(context,SecondActivity.class);
intent.putExtra("LIST_KEY","UNIQUE_LIST_KEY");// pass only key to second activity/fragment
//second activity
SharedPreferences preferences = context.getPreferences(Context.MODE_PRIVATE);
String listJson = preferences.getString(getIntent().getStringExtra("LIST_KEY"),null);//get UNIQUE_LIST_KEY from intent and get string from preferences
if(listJson != null){
List<A lot of objects> list = new Gson().fromJson(listJson, new TypeToken<List<A lot of objects>>(){}.getType());//
}

最新更新