我检查了使用Logcat从Activity传递给Fragment的值。 但是发生“ java.lang.NullPointerException:println需要消息”错误,并且应用程序关闭。 我该如何解决?
我通过这种方式将AString从String传递给Fragment:
Bundle bundle = new Bundle();
bundle.putString("sb", sb.toString());
SlideshowFragment slideshowFragment = new SlideshowFragment();
slideshowFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, slideshowFragment);
fragmentTransaction.commit();
这是SlideshowFragment.java:
public class SlideshowFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
public SlideshowFragment() {
// Required empty public constructor
}
public static SlideshowFragment newInstance(String param1) {
SlideshowFragment fragment = new SlideshowFragment();
Bundle args = new Bundle();
args.putString("sb", param1);
fragment.setArguments(args);
Log.i("TEST", "instance");
return fragment;
}
// I think I Received values on here:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("sb");
Log.i("TEST", "oncreate");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//I could see values on here:
Log.i("TEST onceateview", mParam1);
return inflater.inflate(R.layout.fragment_slideshow, container, false);
}
}
这是Logcat
09-08 18:39:04.102 16245-16245/com.example.nav2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nav2, PID: 16245
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.i(Log.java:207)
at com.example.nav2.ui.slideshow.SlideshowFragment.onCreateView(SlideshowFragment.java:53)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2646)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2416)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2372)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
答案 0 :(得分:0)
SlideshowFragment可以接受字符串,因为参数不是bundle。
SlideshowFragment slideshowFragment = SlideshowFragment.newInstance(sb.toString());