在android中如何将字符串从一个片段传递到另一个片段

在android中如何将字符串从一个片段传递到另一个片段,android,string,android-fragments,store,message-passing,Android,String,Android Fragments,Store,Message Passing,我有两个片段,我想将fragment2字符串发送到fragment1,并将其存储在fragment1中的字符串中。当我试着以正常的方式做这件事时,它会显示一个我已经发布下来的错误。有人请帮帮我 碎片2.2类 Bundle bundle=new Bundle(); bundle.putString("message", value);//value= my value from code Fragmentclass2 frag2=new Fragmentclass2(); frag2.setArg

我有两个片段,我想将fragment2字符串发送到fragment1,并将其存储在fragment1中的字符串中。当我试着以正常的方式做这件事时,它会显示一个我已经发布下来的错误。有人请帮帮我

碎片2.2类

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

 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

我建议您使用
newInstance()
片段常规做法

<>你应该考虑在<<代码>碎片类1/代码>中创建<代码> NeWistStand(<代码> >方法:

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");

我建议您使用
newInstance()
片段常规做法

<>你应该考虑在<<代码>碎片类1/代码>中创建<代码> NeWistStand(<代码> >方法:

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");

您正在Fragmentclass2中设置包。。。它不应该是零碎的吗?另外,请确保您正在显示正在设置参数的对象的实例。您正在Fragmentclass2中设置捆绑包。。。它不应该是零碎的吗?此外,确保正在显示要设置参数的对象的实例,以便清楚地回答。我的意思是使用实例清除代码,我使用片段作为选项卡。所以我需要一个基于此的代码。你有没有尝试在代码中复制我的答案?你只需要按照答案中的要求去做就行了。为了明确起见,您唯一应该替换的是
“您的\u消息”
,即您希望在这些片段之间传递的内容FragmentClass1。newInstance(“您的\u消息”)不起作用。newInstance()函数不起作用您是否如我在回答中所说,在
Fragmentclass1
中定义了静态方法
newInstance()
?不要忘记方法必须是静态的。。你可以从我的答案中复制过去,它肯定会起作用。你能回答清楚吗。我的意思是使用实例清除代码,我使用片段作为选项卡。所以我需要一个基于此的代码。你有没有尝试在代码中复制我的答案?你只需要按照答案中的要求去做就行了。为了明确起见,您唯一应该替换的是
“您的\u消息”
,即您希望在这些片段之间传递的内容FragmentClass1。newInstance(“您的\u消息”)不起作用。newInstance()函数不起作用您是否如我在回答中所说,在
Fragmentclass1
中定义了静态方法
newInstance()
?不要忘记方法必须是静态的。。你可以从我的答案中复制过去,它肯定会起作用。