无法通过捆绑将字符串从一个片段发送到另一个片段

问题描述 投票:0回答:1

我正在尝试通过捆绑包将两个字符串发送到下一个片段,但是即使在我到达第一个片段之前,应用程序也会崩溃。

我在第二个片段中收到此错误:

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

我知道这意味着我要在第二个片段中接收的字符串值意味着该字符串没有任何值,但是我不知道问题出在哪里,因为我要发送的字符串是不为null。

这是我在第一个片段中用于捆绑软件的代码(在onCreatView中使用此代码:]

FragmentAnswer1 frag1 = new FragmentAnswer1();
Bundle args = new Bundle();
args.putString("question_1", question);
args.putString("answer_1", answer);
frag1.setArguments(args);

getFragmentManager().beginTransaction().add(R.id.container, frag1).commit();

这是在第二个片段中接收字符串的代码(当前也在onCreateView中)

question = getArguments().getString("question_1"); // error is in this line
answer = getArguments().getString("answer_1");
question1.setText(question);
rightAnswer.setText(answer);

我已经尝试将上面的代码移到onStart方法中,但仍然遇到相同的错误。我也尝试使用this解决方案,但对我不起作用。我没有找到任何其他解决方案或方法来解决问题。

请让我知道是否需要更多信息。非常感谢您的帮助!

java android android-fragments bundle
1个回答
-1
投票

使用捆绑发送字符串:

//Put the value
YourFragmentName ldf = new YourFragmentName ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);

//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

在新片段的onCreateView中:

//Retrieve the value
if (getArguments() != null) {
    String value = getArguments().getString("YourKey");
}
© www.soinside.com 2019 - 2024. All rights reserved.