简体   繁体   中英

How to store ArrayList of my class in shared preference?

I want to store ArrayList of Polygon objects in shared preference. Can someone help me with this?

To save list:

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();
}

To retrieve list:

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));
}

You can add your ArrayList as serialized object to the SharedPreferences and later deserialize it while reading it from the SharedPreferences. Here's a code sample for that:

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();

Then later retrieve the ArrayList by deserializing it as follows:

 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();
  }

You need to add the ObjectSerializer class to your project too, you can get it from here: ObjectSerializer.java

I referred this answer , and there is an alternate method too for this so you can check that out too

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM