问题
I have a program whose default UI is a ViewPager with a TabLayout. The MainActivity is a CoordinatorLayout. The Viewpager, AppBarLayout, and TabLayout are all wrapped in a RelativeLayout that I intend to use as a container for swapping the main UI out for a different view.
Hosted in one of the ViewPager views is a button. This button communicates with MainActivity via an interface called HelperLinkerListener, which the MainActivity implements. I know that the interface is wired up correctly because I've tested it via logcat.
I'd like to have the button swap out my wrapper RelativeLayout for a new fragment. Here is the current content of my onHelperLinkerClick():
Fragment fragment = new GsonPlaceholder();
Bundle bundle = new Bundle();
bundle.putParcelable("char",charGson);
fragment.setArguments(bundle);
Log.d("logtest", "onHelperLinkerClick: " + bundle.getParcelable("char"));
FragmentTransaction ft = fm.beginTransaction();
ft.remove(getSupportFragmentManager().findFragmentById(R.id.container));
ft.commit();
Here, charGson is a properly defined class implementing Parcelable. The line
ft.remove(getSupportFragmentManager().findFragmentById(R.id.container));
throws the following null pointer exception:
java.lang.NullPointerException: Attempt to read from field 'int android.support.v4.app.Fragment.mContainerId' on a null object reference
It's unclear to me how to fix this problem. Any thoughts?
回答1:
just try changing fm with getSupportFragmentManager()
so it would become
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
回答2:
In my case exactly the same exception was thrown on the attempt to remove fragment that was null. You can insert a code
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction().remove(null).commit();
and see your error log. The problem is that exception will be throwed not on this string, but little bit later somewhere inside of Android sources and you do not see which of your code strings was the reason of the exception.
来源:https://stackoverflow.com/questions/42849509/fragment-transaction-replace-method-throwing-null-object-reference