简体   繁体   中英

NumberFormatException when passing variable through Android Intent

I'm trying to pass 2 variables through a couple of Android Activities. One of them keeps turning up as null on the last page:

The first Activity:

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

The second Activity:

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);

(Note that at this point I printed numRounds in LogCat and it was set to the right number, and not null)

The Third Activity:

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

At this point, the application crashes at the line where I try to parse numRounds to an integer, with a NumberFormatException complaining that it can't parse a null value. There's never a problem with playerChoice, only numRounds. I've tried handling numRounds the exact same way as playerChoice, but nothing seems to work. What's going on? D:

You have to use extras.getInt("numRounds");

because in second Activity you added to putExtra int value:

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

use

numRounds = extras.getInt("numRounds");

intead of

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

because you are passing numRounds as Integer in intent.putExtra("numRounds", numRounds); from second Activity

or pass as if you want to receive as String:

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

As far as i think in your second activity you are setting numRounds a integer value in putExtra() ie the integer variable numRounds thats why it causing problem. either get the numRounds in third activity as directly like extras.getInt("numRounds") or send value as String in second activity ie intent.putExtra("numRounds", numRounds+"");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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