2017-02-22 70 views
1

我有兩個片段,我想將fragment2字符串發送到fragment1並將其存儲在fragment1中的字符串中。當我嘗試以正常方式執行此操作時,它顯示我發佈了一條錯誤消息。有人請幫助我。如何將字符串從一個片段傳遞到另一個android

Fragment2.class

Bundle bundle=new Bundle(); 
bundle.putString("message", value);//value= my value from code 
Fragmentclass2 frag2=new Fragmentclass2(); 
frag2.setArguments(bundle); 

Fragment1.class

final String store= getArguments().getString("message"); 

錯誤日誌:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference 
+0

你正在設置你的包在一個Fragmentclass2 ...不應該是Fragmentclass1?此外,請確定您正在顯示您正在設置參數的對象的實例 –

回答

0

,我建議你使用newInstance()片段一般的做法。

對於您應該考慮在你的Fragmentclass1創建newInstance()方法是這樣的:

public static Fragmentclass1 newInstance(String value) { 
    Fragmentclass1 fragmentclass1 = new Fragmentclass1(); 

    Bundle args = new Bundle(); 
    args.putString("message", value); 
    fragmentclass1.setArguments(args); 

    return fragmentclass1; 
} 

在你Fragmentclass2您撥打:

Fragmentclass1.newInstance("YOUR_MESSAGE") 

這將創建Fragmentclass1所以最後一件事做的是檢索Fragmentclass1的onCreate中的參數。像你這樣做:

final String store= getArguments().getString("message"); 
+0

這是我需要編寫的代碼 –

+0

是的,您可以使用此代碼。你明白嗎? –

+0

你能否清楚回答。我的意思是使用實例清除代碼和所有 –

相關問題