Gson 从共享首选项读取数据



我有一个问题,当我使用 json 将我的 arraylist 保存到共享首选项中并尝试将其加载回我的列表视图时,列表视图不会改变。我读过很多文章,但它们每次都以相同的方式展示。你知道问题可能出在哪里吗?

save.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(thisView.getContext());
        SharedPreferences.Editor editor = sharedPrefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(mainActivity.getResultsArray());
        editor.putString("ResultsArray", json);
        editor.commit();
        Toast saved = Toast.makeText(getContext(), "Uloženo", Toast.LENGTH_LONG);
        saved.show();
    }
});
load.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(thisView.getContext());
        Gson gson = new Gson();
        String json = sharedPrefs.getString("ResultsArray", "");
        Type type = new TypeToken<ArrayList<Result>>(){}.getType();
        ArrayList<Result> results = gson.fromJson(json, type);
        mainActivity.setResultsArray(results);
        mainActivity.getAdapter().notifyDataSetChanged();
        Toast loaded = Toast.makeText(getContext(), "Načteno", Toast.LENGTH_LONG);
        loaded.show();
    }
});

此方法添加到全局类中,以便可以在任何地方使用它。

public static void save_ListToSharedPreferneces(Context context, ArrayList<YourModelClass> recentDataList) {
    SharedPreferences sharedpreferences =
            context.getSharedPreferences("recent_data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(recentDataList);
    editor.putString("recentDataList", json);
    editor.commit();
  }
  public static ArrayList<YourModelClass> get_ListFromSharedPreferneces(Context context) {
    SharedPreferences sharedPrefs = context.getSharedPreferences("recent_data", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPrefs.getString("recentDataList", "");
    Type type = new TypeToken<ArrayList<YourModelClass>>() {
    }.getType();
    ArrayList<YourModelClass> recentDataList= gson.fromJson(json, type);
    return recentDataList;
  }

在保存按钮上,单击"只需调用保存方法",如下所示:

Global.save_ListToSharedPreferneces(context, yourArrayList);

在加载按钮上,单击"只需调用 Get 方法",如下所示:

ArrayList<YourModelClass> yourArrayList=new ArrayList();
yourArrayList = Global.save_ListToSharedPreferneces(context);
//Now set your adapter again:
YourAdapter yourAdapter = new YourAdapter (yourArrayList , getContext());
listview.setAdapter(yourAdapter );

我通过 .add 将结果添加到数组中来修复它。

        ArrayList<Result> results = gson.fromJson(json, type);
        for (Result result: results) {
            mainActivity.getResultsArray().add(result);
        }
        mainActivity.getAdapter().notifyDataSetChanged();

最新更新