来自 getExtras() 的 NullPointerException [英] NullPointerException from getExtras()
本文介绍了来自 getExtras() 的 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建将数据从一个活动传输到另一个活动的意图,如下所示:
I'm creating an intent to transfer data from one activity to another like this :
Intent intent = new Intent(this, ActivityHighScore.class);
intent.putExtra("USERNAME", username);
intent.putExtra("PLAYERMOVES", playerMoves);
this.startActivity(intent);
然后我想在活动开始时检查所有这些数据是否存在,因为它可以从其他来源启动而无需设置这些数据.我使用这个语句:
Then i want to check if all of this data exists as the activity starts, as it can be started from other sources without this data being set. Im using this statement:
Bundle bundle = getIntent().getExtras();
if (!bundle.getString("USERNAME").equals(null) && bundle.getInt("PLAYERMOVES") != 0){
String username = bundle.getString("USERNAME");
int playerMoves = bundle.getInt("PLAYERMOVES");
addHighScore(username, playerMoves);
}
但这会导致空指针异常,我完全确定是如何发生的.我以为我正在掌握字符串和 .equals(),但我认为它...任何帮助将不胜感激.谢谢.
But this causes a null pointerexception and I'm entirely sure how. I thought I was getting to grips with Strings and .equals(), but I think its that... Any help would be greatly appreciated. Thanks.
推荐答案
替换
Bundle bundle = getIntent().getExtras();
if (!bundle.getString("USERNAME").equals(null) && bundle.getInt("PLAYERMOVES") != 0){
String username = bundle.getString("USERNAME");
int playerMoves = bundle.getInt("PLAYERMOVES");
addHighScore(username, playerMoves);
}
与
if (getIntent().getStringExtra("USERNAME") != null && (getIntent().getIntExtra("PLAYERMOVES", 0) != 0){
String username = bundle.getString("USERNAME");
int playerMoves = bundle.getInt("PLAYERMOVES");
addHighScore(username, playerMoves);
}
这篇关于来自 getExtras() 的 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文