FET FET - 3 months ago 19
Android Question

Expected BEGIN_ARRAY but was BEGIN_OBJECT | ArrayList issue

I'm using the Gson library to save and retrieve an ArrayList of Players Objects.

My onStop()

protected void 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());

My onCreate important part

ArrayList<Player> playersNoGuard;
RecyclerView myList;

protected void onCreate(Bundle savedInstanceState) {

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


But when this Activity is run, I get the following error log:

Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

What's wrong in this code?


You probably write to the same preferences entry somewhere else. Ensure that your key (GUARD) is unique throughout the application.