簡體   English   中英

getStringExtra() 總是拋出 NullPointerException

[英]getStringExtra() always throws NullPointerException

主要活動:

Intent intent = new Intent(Main.this, Secondary.class);

intent.putExtra("name",value);

startActivity(intent);

次要活動:

String value = getIntent().getStringExtra("name")

這里有什么問題? 我已經搜索了很多沒有成功...

謝謝

嘗試這個:

在MainActivity中:

//Make sure Secondary is an Activity name. Secondary.class.

Intent intent = new Intent(MainActivity.this, Secondary.class);
intent.putExtra("name",value);
startActivity(intent);

在輔助活動中:

String value = getIntent().getExtras().getString("name");

您需要先獲取包,然后從中提取字符串。

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    bundle.getString("name");
}

兩者都應該有效。 第二個是檢查bundle是否為null。

調用putExtra(...) ,請確保value對象是String 如果要傳遞任何其他對象,請確保顯式調用value.toString() ,尤其是在處理GUI組件時。

有關更多信息,請參閱此處: Android Intent.getStringExtra()返回null

我已經使用過這種方法了。 只需確保值具有值或已初始化。您可以使用LogSystem.out.println(value); .putExtra之后查看(在控制台選項卡中)value是否為null。 在第二次活動中也是如此。

改變這一行

String value = getIntent().getStringExtra("name");

到這一行

String value = getIntent().getString("name");

我發現我的代碼中存在問題,這是我的錯。 這不是意圖問題。 謝謝你們。

你可以試試這個 -->

intent.putExtra("name", textView.getText().toString());

如果錯誤仍然發生,請簽入您正在使用正確 id 路徑的第二個活動...:-

value = findViewById(R.id.);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM