开发者

Null Pointer Exception while using putExtra and getExtras

开发者 https://www.devze.com 2023-03-20 18:08 出处:网络
I\'m trying to use putExtra and getExtras to pass some information in an android game I\'m writing (it\'s a score). When I\'m passing it, I use this code in the one class to put in the information:

I'm trying to use putExtra and getExtras to pass some information in an android game I'm writing (it's a score). When I'm passing it, I use this code in the one class to put in the information:

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开发者_C百科");

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. 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. Using 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() method. To simply add a String to the Intent, use Intent.putExtra(String tag, String value) and get it using Intent.getStringExtra(String tag). I've made this mistake myself many times; it's not very user-friendly xD

0

精彩评论

暂无评论...
验证码 换一张
取 消