簡體   English   中英

在Android中傳遞大型復雜對象

[英]Passing Large, Complex Objects in Android

我正在編寫一個有趣的項目,該項目需要自定義對象內的自定義對象(例如:All_Animals,All_Dogs,All_Labs,My_Lab類型的東西)。 問題是我需要將一個對象從一個活動傳遞到另一個活動,但是該對象具有其他自定義對象的ArrayLists作為變量。 我顯然可以將所有內容都轉換為字符串,然后通過putExtra()傳遞給它,但這將需要大量額外的代碼,並且保持事物的持久性和組織性將變得棘手。

無論如何,我的問題是在Java中(特別是在android中)將帶有ArrayLists作為變量的復雜自定義對象從一個Activity傳遞到另一個Activity的最佳方法是什么?

在舊手機(例如Samsung S4 Mini)中,將大數據(包括base64圖像)傳遞到Intent中可能是一個問題。

在這種情況下,我希望使用數據庫。 如果您不想使用數據庫,則可以使用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());//
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM