[英]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.