简体   繁体   中英

Trouble Passing a Value Through Intent to new Activity

So i'm struggling a bit here to get the values from one activity passed to another. I've tried everything and have looked elsewhere here, but everything I've found didn't work or was unrelated to my issue.

I'm instantiating the intent and using Extras to pass the value. I'm using Eclipse and it's not giving any errors in the IDE. According to LogCAT, it's a NullExceptionPointer Error getting thrown out as i'm using the getIntExtra() method of the intent.

Here's the code from Main Activity:

int tempScore = GUESS_COUNT;
Intent intent = new Intent(getApplicationContext(), SubmitScore.class);
intent.putExtra("PASSED_SCORE", tempScore);
startActivity(intent);

And here's the code from the new activity:

private Intent i = getIntent(); //declared in the class header
tempScore = i.getIntExtra("PASSED_SCORE", 999); //exists inside of a private method for the class 
//(ALSO: THIS tempScore is a private int variable localized to only this class, so that's not the problem)

The moment it tries to store the getIntExtra() returned value to tempScore, it throws the NullPointerException error. Meaning: it's trying to pull a value where there is none. Shouldn't it push 999 as the default value at least though? Why the Error instead? Also, why did the value not getting pushed to the new activity? Thanks in advance for your help. JRad

private Intent i = getIntent(); //declared in the class header

FYI, there is no intent available at that time so you can't use getIntent() . Instead, declare it inside the onCreate() .

You have to check first that you are passing Intent is not null like:

if(i.getExtras()!=null)
{
    tempScore = i.getExtras().getString("PASSED_SCORE");
}

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