【问题标题】:How to pass string from one fragment to another in android如何在android中将字符串从一个片段传递到另一个片段
【发布时间】:2017-07-12 21:09:34
【问题描述】:

我有两个片段,我想将片段 2 字符串发送到片段 1 并将其存储在片段 1 中的字符串中。当我尝试以正常方式执行此操作时,它会显示我已发布的错误。有人请帮帮我。

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

【问题讨论】:

  • 您将捆绑包设置在 Fragmentclass2 中...不应该是 Fragmentclass1 吗?另外,请确保您正在显示您正在设置参数的对象的实例

标签: android string android-fragments store message-passing


【解决方案1】:

我建议你使用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");

【讨论】:

  • 你能回答清楚吗。我的意思是使用实例和所有的清晰代码
  • 我正在为标签使用片段。所以我需要一个基于此的代码
  • 您是否尝试过在您的代码中复制我的答案?您只需要完全按照答案中的方式进行操作即可。为了清楚起见,您应该替换的唯一内容是 "YOUR_MESSAGE" 与您想要在这些片段之间传递的内容
  • Fragmentclass1.newInstance("YOUR_MESSAGE") 不起作用。 newInstance() 函数不起作用
  • 您是否像我在回答中所说的那样在Fragmentclass1 中定义了静态方法newInstance()?不要忘记该方法必须是静态的。您可以从我的答案中复制并过去,它肯定会起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
相关资源
最近更新 更多