0

I have an list of customer object. I need to read them from shared preferences and check for particular object by id with my new object and replace the old one in list with new object and write it to back to pref. This is what I am doing..Is it right?

List<School> schools = readFromPref();
ListIterator<School> iterator = schools.listIterator();
while (iterator.hasNext()) {
School oldSchool = iterator.next();
if (oldSchool.getId().equalsIgnoreCase(newSchool.getId())) {
        iterator.set(newSchool);
        schools.add(newSchool);
    }
}
writeToPref(schools);
Komal12
  • 3,340
  • 4
  • 16
  • 25
Monique890
  • 93
  • 1
  • 7

3 Answers3

0

You can use Enhanced For loop to get and update data in your ArrayList.

ArrayList<School> schools = readFromPref();
            int i=0;
            for(School oldSchool : schools){  //Enhanced For loop
                if(oldSchool.getId().equalsIgnoreCase(newSchool.getId())){
                    oldSchool.setId(newSchool.getId());
                    schools.set(i, oldSchool);
                }
                i++;
            }
            writeToPref(schools);

Here is the link of how to save and retrive Object from SharedPreference using Gson.

Viraj Patel
  • 2,113
  • 16
  • 23
0

Remove schools.add(newSchool); because iterator.set(newSchool); is updating your school list already.

And everything looks good

Balu Sangem
  • 712
  • 4
  • 16
0

Store your data in form of map where key will be the id of your object,and update the object on key basis