这是我的代码,当我点击Item时,我尝试插入数据以共享Preference。
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.popup_Favorite:
songList = songRespones.getSongs();
SharedPreferences sharedPreferences = getContext().getSharedPreferences(
SharePreferenceKey.SONG_LIST, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String songJson = new Gson().toJson(songList.get(position));
editor.putString(SharePreferenceKey.SONG_LIST, songJson);
editor.apply();
showMessage("អ្នកបានរក្សាទុក");
break;
case R.id.popup_cencel:
showMessage("Cancel");
break;
}
return false;
}
});
以下是我想从共享首选项中获取数据的代码
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences sharedPreferences = getContext().getSharedPreferences(
SharePreferenceKey.SONG_LIST, Context.MODE_PRIVATE);
String getSongJson = sharedPreferences.getString(SharePreferenceKey.SONG_LIST, "N/A");
List<SongRespones> songList;
if (!getSongJson.equals("N/A")) {
Type type = new TypeToken<List<SongRespones>>(){}.getType();
songList = new Gson().fromJson(getSongJson, type);
Log.e("ppppp", songList.size() + "");
}
}
但我无法得到它。它显示以下错误:
FATAL EXCEPTION: main Process: com.vichit.khmersong, PID: 20040
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.Gson.fromJson(Gson.java:899)
at com.google.gson.Gson.fromJson(Gson.java:852)
at com.google.gson.Gson.fromJson(Gson.java:801)
请帮帮我:
答案 0 :(得分:0)
您正在存储json对象,因为songList.get(position)
将返回一个对象
更改此行
String songJson = new Gson().toJson(songList.get(position));
到这个
String songJson = new Gson().toJson(songList);