首页 > 解决方案 > 如何将数组列表存储在共享首选项中并在另一个片段中访问

问题描述

我想将此数组列表数据保存在 sharedpreferences 中并在另一个片段中访问该数据。请给我建议

数组列表内容如下

public String productname;
public String productunit;
public String productquantity;
public String productprice;
public String productdiscount;

标签: androidsharedpreferencessectionedrecyclerviewadapter

解决方案


这是解决方案,第 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”并创建其对象。

希望这会帮助你。


推荐阅读