JustAGuy
JustAGuy

Reputation: 23

I'm trying to pass an Object which contains an ArrayList and some other variables

I'm trying to to pass a parcelable Object between two activities (a game activity and a pause screen activity) because i need to save and restore the position of the enemies on screen, the score and the timer. Now, when i did it i got the score and the timer, but not the enemies. I tweaked around a bit and found out that the bitmaps i had in the enemy classes could likely be a problem so i solved it with strings containing the bitmap location. Now i had a couple other things to sort out and it all came down to me making a Bundle and putting the parcelable object in said bundle, passing it to the other activity. Now, i only get ClassNotFoundException when unmarshalling errors. This is the code i'm working with:

First Activity when pausing

Intent intent = new Intent(GameActivity.this, PauseScreenActivity.class);
Bundle b = new Bundle();
gameState = new GameState(new ArrayList<>(customGameView.getEnemies()), score, timeLeftInMillis, xPosition, yPosition);
b.putParcelable("gameState", gameState);
intent.putExtra("bundle", b);
startActivity(intent);

Second Activity retrieving the data

Bundle b = getIntent().getBundleExtra("bundle");
gameState = b.getParcelable("gameState");

Second Activity sending back the data

Intent intent = new Intent(PauseScreenActivity.this, GameActivity.class);
Bundle b = new Bundle();
b.putParcelable("gameState", gameState);
intent.putExtra("bundle", b);
startActivity(intent);

First Activity retrieving the data

Bundle b = getIntent().getBundleExtra("bundle");
gameState = b.getParcelable("gameState");

Now the errors are coming from the second activity's onCreate with the b.getParcelable("gameState");. I'll appreciate all the help, thanks in advance.

Upvotes: 1

Views: 252

Answers (1)

cactustictacs
cactustictacs

Reputation: 19562

From the Bundle#getParcelable docs

Note: if the expected value is not a class provided by the Android platform, you must call setClassLoader(java.lang.ClassLoader) with the proper ClassLoader first. Otherwise, this method might throw an exception or return null.

The way I've always seen people recommend (which is a bit less complicated than messing with ClassLoaders!) is to just set it as an Extra on the Intent:

Intent intent = new Intent(GameActivity.this, PauseScreenActivity.class);
gameState = new GameState(new ArrayList<>(customGameView.getEnemies()), score, timeLeftInMillis, xPosition, yPosition);
intent.putExtra("gameState", gameState);
startActivity(intent);

and then to unparcel it

gameState = getIntent().getParcelableExtra("gameState");

which is much more friendly

If that doesn't work you might want to post your GameState class and the stack trace from the exception so people can see what's up

Upvotes: 0

Related Questions