android - 如何将数组列表存储在共享首选项中并在另一个片段中访问
问题描述
我想将此数组列表数据保存在 sharedpreferences 中并在另一个片段中访问该数据。请给我建议
数组列表内容如下
public String productname;
public String productunit;
public String productquantity;
public String productprice;
public String productdiscount;
解决方案
这是解决方案,第 1 步:创建一个类
共享偏好
public static final String FAVORITES = "PRODUCTS";
private SharedPreferences settings;
private Editor editor;
public SharedPreference() {
super();
}
现在代码保存 ArrayList
public void saveArrayList(Context context, List<String> unread_ids) { settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME, Context.MODE_PRIVATE); editor = settings.edit(); Gson gson = new Gson(); String jsonFavorites = gson.toJson(unread_ids); editor.putString(FAVORITES, jsonFavorites); editor.apply(); }
现在代码来保存 Arraylist
public ArrayList<String> getSavedList(Context context) {
// SharedPreferences settings;
List<String> unReadId;
settings = context.getSharedPreferences(AppConfig.KEY_PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, "");
Gson gson = new Gson();
String[] favoriteItems = gson.fromJson(jsonFavorites,
String[].class);
unReadId = Arrays.asList(favoriteItems);
unReadId = new ArrayList<>(unReadId);
} else {
return new ArrayList<String>();
}
return (ArrayList<String>) unReadId;
}
保存列表的代码:
sharedPreferences.saveArrayList(context, <YOUR LIST NAME>);
现在编写代码以在其他片段中获取您的 Arraylist
<LIST NAME> = sharedPreference.getSavedList(getActivity());
在获取和保存数组列表之前,您必须声明“sharedPreference”并创建其对象。
希望这会帮助你。
推荐阅读
- android - 导航到片段时传递安全参数
- functional-programming - 在 elementwise Scheme 中添加任意列表的列表
- c# - 创建和初始化从字典派生的类
- c# - 如何将 WebApi 与带有 GET 响应的重定向 uri 结合使用?ASP.NET MVC,C#
- javascript - React - 如何回溯历史并删除前向历史?
- botframework - 来自 Web 客户端的 BotFramework 消息丢失了文本
- python - 为什么我会为 pandas Series.apply 和 DataFrame.applymap 得到不同的结果?
- flutter - 如何动态更改 SliverAppBar 高度
- assembly - 组装 - 我哪里出错了?
- python - 带有硒的软件给出断言python3