2016-02-08 50 views
1

如何從另一個活動的不同意圖傳遞不同的值。即將來自兩個不同意圖的數據從一個活動傳遞到另一個活動

活動A:

按鈕a .onclick {

intent.putExtra("name", screenname); 

    intent.putExtra("email", description); 

    intent.putExtra("pic", twitterImage); 

    startActivity(intent); 

}

ButtonB。的onClick {

intent.putExtra("anothervalue", json_object.toString()) 

}

活性B:

Intent intent = getIntent(); 

    String getValue = intent.getStringExtra("value from any of the button clicked") 
+0

您在示例中使用的鍵和值具有誤導性。鍵和值應該不同,並且getStringExtra中使用的鍵與putExtra中使用的鍵相同。 – Tapani

回答

2

雖然大衛勞卡答案基本上是正確的,你可能會面臨NullPointerException

getIntent().getStringExtra("firstvalue")如果名稱'firstvalue'沒有值,將會導致NPE。

你應該檢查值是否像這樣存在。

if(getIntent().hasExtra("firstvalue")) { 
    String firstvalue = getIntent().getStringExtra("firstvalue"); 
} 
+0

謝謝,我嘗試過它,但仍然有一個問題,我只測試了一個項目,實際上按鈕A發送的值超過了,我不想檢查是否全部爲空,因爲值可以是後來改變了,intent.putExtra(「name」,screenname); intent.putExtra(「email」,description); intent.putExtra(「pic」,twitterImage); startActivity(intent); –

+0

如何發送整個對象? 或檢查差異值? 例如:A正在發送姓名,電子郵件,圖片和B正在發送dob,密碼。你可以檢查意圖是否有'name'或'dob'。 這樣你只需要檢查'name'和'dob'。並相應地提取其餘部分。 – Hein

0
String getValue = intent.getStringExtra("firstvalue") // in order to get the first value that was set when user clicked on buttonA 

String getValue = intent.getStringExtra("anothervalue") // in order to get the the value that was set when user clicked on buttonB 
0

Activity B代碼應該是這樣的

Intent intent = getIntent(); 
String firstvalue = intent.getStringExtra("firstvalue"); 
String anothervalue = intent.getStringExtra("anothervalue"); 

if(firstvalue != null) 
    // called from Button A click 
else if(secondvalue != null) 
    // called from Button B click 
0
Intent intent = getIntent(); 
String getValue = null; 

if(intent.hasExtra("firstvalue")){ 

getValue = intent.getStringExtra("firstvalue"); 

} 

if(intent.hasExtra("anothervalue")){ 

getValue = intent.getStringExtra("anothervalue"); 

} 
1

@Mandeep答案是正確的。但是如果你有更多來自活動的價值,那麼這就是解決方案。感謝Mandeep

Intent i = getIntent(); 
String getValue1,getValue2,getValue3; 

if(i.hasExtra("AFirstValue") && i.hasExtra("ASecondValue") && i.hasExtra("AThirdValue")){ 

getValue1 = i.getStringExtra("AFirstvalue"); 
getValue2 = i.getStringExtra("ASecondValue"); 
getValue3 = i.getStringExtra("AThirdValue"); 

} 

if(i.hasExtra("anotherFirstvalue") && i.hasExtra("anotherSecondvalue") && i.hasExtra("anotherThirdvalue")){ 

getValue1 = i.getStringExtra("anotherFirstvalue"); 
getValue2 = i.getStringExtra("anotherSecondvalue"); 
getValue3 = i.getStringExtra("anotherThirdvalue"); 

} 
相關問題