Fragment Transaction .replace() method throwing null object reference

故事扮演 提交于 2019-12-12 05:59:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!