我正在使用 Gson 库来保存和检索玩家对象的 ArrayList。
我的 onStop()
@Override
protected void onStop() {
super.onStop();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String guardJSON = gson.toJson(playersNoGuard);
editor.putString(GUARD, guardJSON);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
我的 onCreate 重要部分
ArrayList<Player> playersNoGuard;
RecyclerView myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_players_guard);
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
String guardJSON = prefs.getString(GUARD, null);
Type arrayListPlayers = new TypeToken<ArrayList<Player>>(){}.getType();
Gson gson = new Gson();
if(guardJSON != null) {
playersNoGuard = gson.fromJson(guardJSON, arrayListPlayers);
}
// Get the players and remove the Clairvoyant
Intent intent = this.getIntent();
playersNoGuard = intent.getParcelableArrayListExtra("PLAYERS");
[...] // Code skipped
}
但是当此活动运行时,我收到以下错误日志:
引起原因:java.lang.IllegalStateException:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT
这段代码有什么问题?
您可能会在其他地方写入相同的首选项条目。确保您的密钥 (GUARD
) 在整个应用程序中是唯一的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)