如何在共享首选项中存储我的班级的ArrayList?

时间:2018-07-03 13:15:04

标签: java android

我想以共享首选项存储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));
}

2 个答案:

答案 0 :(得分:0)

您可以将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

我提到了this answer,为此也有另一种方法,因此您也可以检查一下

答案 1 :(得分:-5)

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