這是我的救命程序代碼,這將節省比分,日期和玩家名字的排行榜:保存和檢索的ArrayList到SharedPreferences
mLeaderboardlist = new ArrayList<>();
Leaderboardmodel s = new Leaderboardmodel();
s.setDate("07/24/17");
s.setName(player.getText().toString());
s.setScore(Integer.parseInt(String.valueOf(yourScore.getText())));
Tab1Normal.mLeaderboardlist.add(s);
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(s);
prefsEditor.putString("MyObject", json);
prefsEditor.apply();
prefsEditor.commit();
這是我的也是買賣sharedpreference的檢索程序代碼:
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getActivity().getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("MyObject", "");
Type type = new TypeToken<ArrayList<Leaderboardmodel>>(){}.getType();
ArrayList<Leaderboardmodel> leaderboard= gson.fromJson(json, type);
Collections.sort(leaderboard);
adapter = new ListLeaderBoardAdapter(getActivity(), leaderboard);
lvLeaderboardlist.setAdapter(adapter);
保存保存部分工作的罰款,但恢復部分顯示錯誤,使應用程序崩潰,錯誤顯示:
com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:預期BEGIN_ARRAY但BEGIN_OBJECT位於第1行第2列路徑$
您是否嘗試在'String json = appSharedPrefs.getString(「MyObject」,「」);'上放置一個斷點,以查看它存在於哪裏..? – AsfK
我應該怎麼做先生? – Luffy
檢查JSON與Android調試器聯繫(使用調試..)看到這個鏈接:https://developer.android.com/studio/debug/index.html – AsfK