如何编辑存储在共享首选项中的自定义对象数组列表中的数据?我正在使用这个 class 来存储和访问
how to edit the data present in arraylist of custom objects stored in shared preference?? i am using this class to storing and accessing
public class PrefConfigForProducts {
private static final String LIST_KEY_PRODUCTS = "List_Key_Products";
public static void writeinPref(Context context, List<List_addProducts> list_addProducts2){
Gson gson2=new Gson();
String jsonString2=gson2.toJson(list_addProducts2);
SharedPreferences sharedPreferences2= PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor2=sharedPreferences2.edit();
editor2.putString(LIST_KEY_PRODUCTS,jsonString2);
editor2.apply();
}
public static List<List_addProducts> readinPref(Context context){
SharedPreferences sharedPreferences2=PreferenceManager.getDefaultSharedPreferences(context);
String jsonString2=sharedPreferences2.getString(LIST_KEY_PRODUCTS,"");
Gson gson2=new Gson();
Type type2=new TypeToken<ArrayList<List_addProducts>>() {}.getType();
List<List_addProducts> list_addProducts2=gson2.fromJson(jsonString2,type2);
if(list_addProducts2==null){
list_addProducts2=new ArrayList<>();
}
return list_addProducts2;
}
}
简单地说,
1) 使用一个参数创建新方法 index 然后将 SharedPreferences 数据读取到您的 List 对象.
2) 然后使用索引从该列表 访问对象并修改它
3) 使用 set 方法
更新 List 中的对象
4) 保存列表 回到 SharedPreferences
1st) 从 pref 获取列表并将其存储在数组中。
2)在该数组中添加新数据。
3) 再次将整个列表保存在 pref
public class PrefConfigForProducts { private static final String LIST_KEY_PRODUCTS = "List_Key_Products";
public static void writeinPref(Context context, List<List_addProducts> list_addProducts2){
Gson gson2=new Gson();
String jsonString2=gson2.toJson(list_addProducts2);
SharedPreferences sharedPreferences2= PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor2=sharedPreferences2.edit();
editor2.putString(LIST_KEY_PRODUCTS,jsonString2);
editor2.apply();
}
public static List<List_addProducts> readinPref(Context context){
SharedPreferences sharedPreferences2=PreferenceManager.getDefaultSharedPreferences(context);
String jsonString2=sharedPreferences2.getString(LIST_KEY_PRODUCTS,"");
Gson gson2=new Gson();
Type type2=new TypeToken<ArrayList<List_addProducts>>() {}.getType();
List<List_addProducts> list_addProducts2=gson2.fromJson(jsonString2,type2);
if(list_addProducts2==null){
list_addProducts2=new ArrayList<>();
}
return list_addProducts2;
}
}
简单地说,
1) 使用一个参数创建新方法 index 然后将 SharedPreferences 数据读取到您的 List
2) 然后使用索引从该列表
3) 使用 set 方法
更新 List4) 保存列表
1st) 从 pref 获取列表并将其存储在数组中。 2)在该数组中添加新数据。 3) 再次将整个列表保存在 pref