简体   繁体   English

无法通过意图将价值传递给新活动

[英]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. 我正在实例化意图,并使用Extras传递值。 I'm using Eclipse and it's not giving any errors in the IDE. 我正在使用Eclipse,并且在IDE中未给出任何错误。 According to LogCAT, it's a NullExceptionPointer Error getting thrown out as i'm using the getIntExtra() method of the intent. 根据LogCAT的说法,这是NullExceptionPointer错误,因为我正在使用意图的getIntExtra()方法。

Here's the code from Main Activity: 这是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. 尝试将getIntExtra()返回的值存储到tempScore时,它会引发NullPointerException错误。 Meaning: it's trying to pull a value where there is none. 意思是:它试图在没有值的地方拉一个值。 Shouldn't it push 999 as the default value at least though? 它是否至少应将999推为默认值? 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(); 私人意图i = getIntent(); //declared in the class header //在类标题中声明

FYI, there is no intent available at that time so you can't use getIntent() . 仅供参考,当时没有可用的意图,因此您不能使用getIntent() Instead, declare it inside the onCreate() . 而是在onCreate()声明它。

You have to check first that you are passing Intent is not null like: 您必须先检查您正在传递的Intent不为null,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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