简体   繁体   English

Null 使用 putExtra 和 getExtras 时出现指针异常

[英]Null Pointer Exception while using putExtra and getExtras

I'm trying to use putExtra and getExtras to pass some information in an android game I'm writing (it's a score).我正在尝试使用 putExtra 和 getExtras 在我正在编写的 android 游戏中传递一些信息(这是一个分数)。 When I'm passing it, I use this code in the one class to put in the information:当我传递它时,我在一个 class 中使用此代码来输入信息:

Intent winScreen = new Intent(context, WinScreen.class);
winScreen.putExtra("score", "123");

And when I'm getting it, I'm using:当我得到它时,我正在使用:

Intent x=new Intent(this, GameCall.class);
Bundle ebundle = x.getExtras();
String score = (String) x.getExtras().getSerializable("score");

I'm just trying to test with a sample score right now, so I don't think setting the value correctly is the problem.我现在只是想用一个样本分数进行测试,所以我认为正确设置值不是问题所在。 That was the suggestion I saw elsewhere for why such a null pointer would occur.这就是我在其他地方看到的关于为什么会出现这样的 null 指针的建议。 I know it understands "score" as an extra.我知道它将“分数”理解为额外的。 So I am stumped as to where the information is being lost!所以我对信息丢失的地方感到困惑!

When you use an Intent to start a new Activity, you must use getIntent() to get that specific instance of the intent.当您使用Intent启动一个新的 Activity 时,您必须使用getIntent()来获取该 Intent 的特定实例。 Using Intent x=new Intent(this, GameCall.class);使用Intent x=new Intent(this, GameCall.class); won't work.不会工作。 Try the following code:试试下面的代码:

Intent x= this.getIntent(); //in the WinScreen activity
String score = (String) x.getStringExtra("score");

Using Intent.getExtras() returns a Bundle that you previously added to the Intent with the Intent. putExtras()使用Intent.getExtras()返回一个Bundle ,它是您之前使用 Intent 添加到 Intent 中的Intent. putExtras() Intent. putExtras() method. Intent. putExtras()方法。 To simply add a String to the Intent, use Intent.putExtra(String tag, String value) and get it using Intent.getStringExtra(String tag) .要简单地将字符串添加到 Intent,请使用Intent.putExtra(String tag, String value)并使用Intent.getStringExtra(String tag)获取它。 I've made this mistake myself many times;我自己多次犯过这个错误; it's not very user-friendly xD这不是很人性化xD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM