簡體   English   中英

如何在共享首選項中存儲我的班級的ArrayList?

[英]How to store ArrayList of my class in shared preference?

我想以共享首選項存儲Polygon對象的ArrayList。 有人可以幫我弄這個嗎?

要保存列表:

public void savePolygonObjects(Context context){
    SharedPreferences mPrefs = context.getSharedPreferences("MyPref", context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = mPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(polygonArrayList);
    prefsEditor.putString("myJson", json);
    prefsEditor.commit();
}

要檢索列表:

SharedPreferences mPrefs = getSharedPreferences("MyPref", 
                                     getApplicationContext().MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("myJson", "");
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();

for(int i=0; i< array.size(); i++){
    polygonArrayList.add(gson.fromJson(array.get(i), Polygon.class));
}

您可以將ArrayList作為序列化對象添加到SharedPreferences ,然后在從SharedPreferences中讀取它時反序列化它。 這是一個代碼示例:

ArrayList<Polygon> polygonList = new ArrayList<Polygon>();

// Add the data to the list

// Serializing and adding the ArrayList to the SharedPreferences
SharedPreferences prefs = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
  Editor editor = prefs.edit();
  try {
    editor.putString(POLYGONS, ObjectSerializer.serialize(polygonList));
  } catch (IOException e) {
    e.printStackTrace();
  }
  editor.commit();

然后,通過反序列化來檢索ArrayList ,如下所示:

 SharedPreferences prefs = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);

  try {
    polygonList = (ArrayList<POLYGON>) ObjectSerializer.deserialize(prefs.getString(POLYGONS, ObjectSerializer.serialize(new ArrayList<POLYGON>())));
  } catch (IOException e) {
    e.printStackTrace();
  } catch (ClassNotFoundException e) {
    e.printStackTrace();
  }

您還需要將ObjectSerializer類添加到您的項目中,您可以從這里獲取它: ObjectSerializer.java

我提到了這個答案 ,並且對此還有另一種方法,因此您也可以檢查一下

List<Person> customer = new ArrayList<Person>();
Person p = .....;
customer.add(person);

暫無
暫無

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

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