繁体   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