繁体   English   中英

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

[英]Trouble Passing a Value Through Intent to new Activity

所以我在这里有点挣扎,无法将一项活动的价值传递给另一项活动。 我已经尝试了所有方法,并在此处找到了其他地方,但是我发现的所有方法均无效或与我的问题无关。

我正在实例化意图,并使用Extras传递值。 我正在使用Eclipse,并且在IDE中未给出任何错误。 根据LogCAT的说法,这是NullExceptionPointer错误,因为我正在使用意图的getIntExtra()方法。

这是Main Activity中的代码:

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

这是新活动的代码:

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)

尝试将getIntExtra()返回的值存储到tempScore时,它会引发NullPointerException错误。 意思是:它试图在没有值的地方拉一个值。 它是否至少应将999推为默认值? 为什么是错误? 另外,为什么价值没有被推到新活动中呢? 在此先感谢您的帮助。 杰拉德

私人意图i = getIntent(); //在类标题中声明

仅供参考,当时没有可用的意图,因此您不能使用getIntent() 而是在onCreate()声明它。

您必须先检查您正在传递的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