我正在尝试传递包含ArrayList和其他一些变量的对象

问题描述

我正试图在两个活动(游戏活动和暂停屏幕活动)之间传递可包裹物体,因为我需要保存和恢复敌人在屏幕上的位置,得分和计时器。现在,当我这样做时,我得到了比分和计时器,但没有敌人。我进行了一些调整,发现我在敌方职业中拥有的位图可能是个问题,因此我使用包含位图位置的字符串解决了该问题。现在,我还有其他几件事要整理,这一切归结于我制作了一个Bundle并将可打包对象放入所说的bundle中,然后将其传递给其他活动。现在,我只遇到ClassNotFoundException when unmarshalling错误。这是我正在使用的代码

暂停时

一个活动

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);

第二活动检索数据

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

第二活动发送回数据

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

首次活动检索数据

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

现在,错误自带b.getParcelable("gameState");的第二个活动的onCreate。非常感谢您的帮助。

解决方法

Bundle#getParcelable docs

注意:如果期望值不是Android平台提供的类,则必须首先使用正确的setClassLoader(java.lang.ClassLoader)调用ClassLoader否则,此方法可能会引发异常或返回null

我经常看到的人们推荐的方式(这比搞砸ClassLoaders复杂得多!)只是将其设置为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);

然后取消包裹

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

much more friendly

如果这不起作用,您可能要发布您的GameState类,并从异常中跟踪堆栈,以便人们可以看到最新情况

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...