我正在尝试使用 putExtra 和 getExtras 在我正在编写的 Android 游戏中传递一些信息(这是一个分数)。当我传递它时,我在一个类中使用这段代码来输入信息:
Intent winScreen = new Intent(context, WinScreen.class);
winScreen.putExtra("score", "123");
当我得到它时,我正在使用:
Intent x=new Intent(this, GameCall.class);
Bundle ebundle = x.getExtras();
String score = (String) x.getExtras().getSerializable("score");
我现在只是想用样本分数进行测试,所以我认为正确设置值不是问题所在。这是我在其他地方看到的关于为什么会出现这样的空指针的建议。我知道它把“分数”理解为额外的。所以我很困惑信息在哪里丢失了!
最佳答案
当您使用 Intent
启动一个新的 Activity 时,您必须使用 getIntent()
来获取该 Intent 的特定实例。使用 Intent x=new Intent(this, GameCall.class);
将不起作用。试试下面的代码:
Intent x= this.getIntent(); //in the WinScreen activity
String score = (String) x.getStringExtra("score");
关于java - 使用 putExtra 和 getExtras 时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6726019/