我有一个问题,当我使用 json 将数组列表保存到共享首选项中并尝试将其加载回 ListView 时, ListView 不会更改。我读过很多文章,但每次都以同样的方式展示。您知道问题出在哪里吗?
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();
}
});
最佳答案
将此方法添加到您的 Global 类中,以便您可以在任何地方使用它。
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 );
关于java - Gson 从共享首选项中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430709/