繁体   English   中英

在读取共享首选项时,只收到一个对象

[英]On read shared preferences , only one object received

我正在尝试将一些对象Array保存到SharedPreferences

它如何在我的应用程序上运行:

我有包含可点击项目的RecyclerView 单击这些项目后,它们将被添加到一个新的数组中。 新数组显示在另一个视图中。 我正在尝试将数组添加到片段的onDestroyView()上的SharedPreferences 这意味着当我杀死片段时,数组将保存在SharedPreferences

现在使用我的代码,在读取数据时,我只从数组中获取最后一个对象,而不是所有对象。

这是我的代码:

private LightsHistory lightsHistory;
    private ArrayList<LightsHistory> lightHistories = new ArrayList<>();

将项目添加到另一个视图:

public void addItemToHistory(int position) {
        String title = mLightsArray.get(position).getLampTitle();
        String desc = mLightsArray.get(position).getLampDesc();
        String imageURL = mLightsArray.get(position).getLampImageUrl();

        lightsHistory = new LightsHistory(imageURL, title, desc);
        lightHistories.clear();
        lightHistories.add(lightsHistory);

        for (int j = 0; j < lightHistories.size(); j++) {
            if (i == 3) {
                i = 0;
            }
            Glide.with(getContext())
                    .load(lightHistories.get(j).getmLightsIMG())
                    .override(150)
                    .into(historyItemsPH.get(i));
            i++;
        }


        saveToSharedPrefs(lightHistories);
    }

保存到 SP

public void saveToSharedPrefs(ArrayList<LightsHistory> lightHistories) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor editor = sharedPrefs.edit();
        Gson gson = new Gson();

        String json = gson.toJson(lightHistories);

        editor.putString(TAG, json);
        editor.commit();
        Log.d(TAG, "saveToSharedPrefs: "+json);
    }

从 SP 读取

public void readFromSharedPrefs() {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        Gson gson = new Gson();
        String json = sharedPrefs.getString(TAG, "");
        Type type = new TypeToken<List<LightsHistory>>() {
        }.getType();
        ArrayList<LightsHistory> arrayList = gson.fromJson(json, type);
        if (arrayList != null) {
            for (int j = 0; j < lightHistories.size(); j++) {
                Log.d(TAG, "readFromSharedPrefs: " + arrayList.get(j).getmLightsTitle()
                        + "\n" + arrayList.get(j).getmLightsDesc()
                        + "\n" + arrayList.get(j).getmLightsIMG());
            }
        }
    }
lightsHistory = new LightsHistory(imageURL, title, desc);
lightHistories.clear();
lightHistories.add(lightsHistory);

您正在调用list.clear()并向其添加一个元素,因此该列表在保存到共享首选项时将只有一个元素。

删除“lightHistory.clear();” 如果要清除数组列表,请将它放在使用方法 saveToSharedPrefs() 之后。

问候。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM