Alex
Alex

Reputation: 1936

override arraylist on shared preferences

I'm saving an arraylist on shared preferences but when i add something new to this array it deletes the old one and displays only the new one.

Here is the save and load array from shared preferences

//SHARED PREFERENCES Save ArrayList
public boolean saveArrayList(SharedListFood list) {
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list.getMlist()); //put in json the list from my model(SharedFoodList) which is the list i provide(itemsAdded)
    editor.putString("testShared", json);
    return editor.commit();     // This line is IMPORTANT !!!
}

//SHARED PREFERENCES Load ArrayList
public ArrayList<String> getArrayList() {

    ArrayList<String> loadArrayList;

    Gson gson = new Gson();
    String json = prefs.getString("testShared", null);
    Type type = new TypeToken<ArrayList<String>>() {
    }.getType();
    loadArrayList = gson.fromJson(json, type);

    return loadArrayList;

}

I add the item here.

   searchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                searchMessage = searchList.getItemAtPosition(position).toString(); //searchMessage gets the value of the pressed item in list

                if(searchMessage.contains("two")){
                    Log.d("alekos","tak"+searchMessage);
                }
                Toast.makeText(AddFood.this, "" + searchMessage, Toast.LENGTH_SHORT).show();

                itemsAdded.add(searchMessage);// made it static so it is created here but displayed in the AddFoodBasket.java
         sharedArray=new SharedListFood(itemsAdded);

                boolean isSuccess= sharedArrayPreferencesHelper.saveArrayList(sharedArray); //sends itemsAdded to saveArrayList in shared preferences
                if (isSuccess) {
                    Toast.makeText(getApplicationContext(),"Personal information saved", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),"Personal information NOT", Toast.LENGTH_LONG).show();
                }
            }
        });

Where itemsAdded is the arraylist i want to add each time

Upvotes: 0

Views: 144

Answers (1)

Viraj S
Viraj S

Reputation: 400

As per my understanding,
1. you have written SharedPreferences.Editor inside saveArrayList().
2. On every single time this method called, you create a new Editor and it replaces the previous one.
3. SharedPreferences stores in key-value pair and you are storing data in the same key every time. (It Replaces previous values with new ones)
4. Your code might be correct for data but the flow is wrong. Try to work on your code- flow.
Hope it helps. :)

Upvotes: 1

Related Questions