通过Android Intent传递变量时的NumberFormatException

时间:2012-07-02 13:32:17

标签: java android

我正在尝试通过几个Android活动传递2个变量。其中一个在最后一页上一直显示为null:

第一个活动:

Intent intent= new Intent(RoundOptionActivity.this, MoveOptionActivity.class);
intent.putExtra("numRounds", "5");
startActivity(intent);

第二项活动:

Bundle extras = getIntent().getExtras(); 
if(extras !=null) {
    numRounds = Integer.parseInt(extras.getString("numRounds"));
}

.........

Intent intent = new Intent(MoveOptionActivity.this, MoveActivity.class);
intent.putExtra("numRounds", numRounds);
intent.putExtra("playerChoice", playerChoice);
startActivity(intent);

(注意,此时我在LogCat中打印了numRounds并将其设置为正确的数字,而不是null)

第三项活动:

Bundle extras = getIntent().getExtras(); 
if(extras !=null) {
    playerChoice = Integer.parseInt(extras.getString("playerChoice"));
    numRounds = Integer.parseInt(extras.getString("numRounds"));
}

此时,应用程序在我尝试将numRounds解析为整数的行崩溃,并且NumberFormatException抱怨它无法解析空值。 playerChoice从来没有问题,只有numRounds。我尝试以与playerChoice完全相同的方式处理numRounds,但似乎没有任何效果。这是怎么回事? d:

3 个答案:

答案 0 :(得分:3)

您必须使用extras.getInt("numRounds");

因为在第二个Activity中您添加了putExtra int 值:

numRounds = Integer.parseInt(extras.getString("numRounds"));

答案 1 :(得分:2)

使用

numRounds = extras.getInt("numRounds");

intead of

numRounds = Integer.parseInt(extras.getString("numRounds"));

因为您从第二个活动intent.putExtra("numRounds", numRounds);中将 numRounds 作为整数传递

或传递,就好像你想收到String:

Intent intent = new Intent(MoveOptionActivity.this, MoveActivity.class);
intent.putExtra("numRounds", numRounds+"");
intent.putExtra("playerChoice", playerChoice);
startActivity(intent);

答案 2 :(得分:1)

据我所知,在你的第二个活动中,你在numExtra()中设置numRounds一个整数值,即整数变量numRounds,这就是它导致问题的原因。或者像第三项活动那样直接获取第三项活动中的numRounds,或者在第二项活动中将值作为字符串发送,即extras.getInt("numRounds")