在共享首选项上覆盖arraylist

时间:2018-12-23 13:56:21

标签: android sharedpreferences

我要在共享首选项上保存一个数组列表,但是当我向该数组添加新内容时,它将删除旧的数组并仅显示新的数组。

这是共享首选项中的保存和加载数组

//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;

}

我在这里添加项目。

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

itemsAdded是我每次想添加的数组列表

1 个答案:

答案 0 :(得分:1)

据我了解,
    1.您已经在SharedPreferences.Editor内写了saveArrayList()
    2.每次调用此方法时,您都会创建一个新的编辑器,它将替换     上一个。
    3. SharedPreferences存储在键值对中,而您将数据存储在同一键中     每次。 (用新值替换以前的值)
    4.您的代码对于数据而言可能是正确的,但是流程是错误的。尝试处理您的代码-    流。
    希望能帮助到你。 :)