[英]Pass data between two fragments
I want to pass data between two Fragment
I am adding this method to the Fragment whose sending data. 我想在两个
Fragment
之间传递数据,我将此方法添加到发送数据的Fragment中。
public void sendData(){
//Put the value
FragmentA fragmentA = new
FragmentA ();
String tag = data.TAGS;
Bundle bundle = new Bundle();
bundle.putString("TAG", tag);
fragmentA.setArguments(bundle);
//Inflate the fragment
FragmentManager fragmentManager=getFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.container, fragmentA)
.addToBackStack(null)
.commit();
}
and in the Fragment which recieve information I am adding this code into the onCreateView
在接收信息的片段中,我将此代码添加到
onCreateView
String tag = getArguments().getString("TAG");
Log.d("valeur", "valeur=" + tag);
the problem is that I am getting data with LOGGer but the app crached and I have this message in the getString
method, 问题是我正在使用LOGGer获取数据,但是应用程序崩溃了,并且在
getString
方法中有此消息,
Exception: Attempt to invoke virtual method 'java.lang.String
android.os.Bundle.getString(java.lang.String)' on a null object reference
SOLUTION: 解:
if(getArguments()!=null){
// log your data here
}
You Made Mistake in setArgument 您在setArgument中犯了错误
Here is Your Modified code 这是您的修改后的代码
Bundle bundle = new Bundle();
bundle.putString("TAG", tag);
FragmentManager fragmentManager=getFragmentManager();
//You need to put setArgument Here
fragmentA.setArguments(bundle);
fragmentManager.beginTransaction()
.add(R.id.container, fragmentA)
.addToBackStack(null)
.commit();
And at your receiving fragment You need to check getArgument whether it is fillup with values or not in onCreateView() method 在接收片段时,您需要检查getArgument是否在onCreateView()方法中填充了值
if(getArgument != null){
String tag = getArguments().getString("TAG");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.