1

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

数组列表内容如下

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

2 回答 2

0

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

希望这会帮助你。

于 2018-12-03T13:06:37.467 回答
0

我之前做过类似的事情请检查此代码

private List<String> list; /// adding checked items to list

在你OnCreate()添加这一行

list = new ArrayList<>(); /// checked items list

并从模型中获取数组并将其存储在本地,请使用下一个。

int searchListLength = items.size();
        for (int i = 0; i < searchListLength; i++) {
            if (items.get(i).isChecked()) {
                items.get(i).getId();
                Log.d("listitem", String.valueOf("id=" + items.get(i).getId()));
                list.add("id=" + items.get(i).getId());
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : list) {
            stringBuilder.append(s);
            stringBuilder.append("&");
        }

  SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor_notaif = notif_array.edit();
            editor_notaif.putString("id", stringBuilder.toString());
            editor_notaif.apply();
            Intent intent = new Intent(MainActivity.this, Filtered_Activity.class);
            startActivity(intent);

在您的另一个活动/片段中

私人字符串 new_result;

SharedPreferences notif_array = getSharedPreferences("items_array", Context.MODE_PRIVATE);
        new_result = notif_array.getString("id", null);
于 2018-12-03T15:14:28.400 回答