Reputation: 417
In my application I am trying to save an ArrayList using SharedPreference and Gson jar file. The Arraylist has objects of Person class which implements Serializable. I want the ArrayList to retain its data when back button is pressed.I have seen a lot of code on Internet but nothing suits me particularly. I have written part of the code seeing various solutions but I'm unsure of where to use it and my code also needs a bit of correction but I am unable to do it because I do not have much experience in programming.
Here is part of my code:
//Saving the arraylist
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Editor editor = prefs.edit();
Gson gson = new Gson();
//String json = gson.toJson(RecipientArray);
for(Person p:RecipientArray){
String json = gson.toJson(p);
editor.putString("RecList", json);
}
editor.commit();
//Retrieving the values
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String json = prefs.getString("RecList", "");
Gson gson = new Gson();
Person p = gson.fromJson(json, Person.class);
RecipientArray.add(p); //RecipientArray is an ArrayList<Person>
Here I am not sure of how to get all Person objects saved earlier. Also I am not sure of where to put these pieces of code. Please help me as soon as possible.
Thanks.
Upvotes: 0
Views: 2144
Reputation: 3921
This code have a problem, because your only put one key "RecList" so that you will put last one Person p to SharedPreferences.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Editor editor = prefs.edit();
Gson gson = new Gson();
//String json = gson.toJson(RecipientArray);
for(Person p:RecipientArray){
String json = gson.toJson(p);
editor.putString("RecList", json);
}
editor.commit();
maybe you can change your key like "RecList_"+number and also save your array.size
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Editor editor = prefs.edit();
Gson gson = new Gson();
//String json = gson.toJson(RecipientArray);
for(int i = 0; i < RecipientArray.size(); i++)
String json = gson.toJson(RecipientArray.get(i));
editor.putString("RecList_"+i, json);
editor.putInt("size",i);
}
editor.commit();
so you can get all string in your SharedPreferences like this
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
int size = prefs.getInt("size");
for(int i = 0;i<size;i++) {
String json = prefs.getString("RecList_"+i, "");
Gson gson = new Gson();
Person p = gson.fromJson(json, Person.class);
RecipientArray.add(p); //RecipientArray is an ArrayList<Person>
}
Upvotes: 3