1

Trying to replace current Fragment to another one by capturing its root view id as container id programatically but getting Null value exception.

  Fragment fragment = MyNewFragment.newInstance(name);
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(this.getView().getRootView().getId(), fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
  • this.getView().getRootView().getId() this might be causing the null pointer. Why don't you use id given in xml file instead of this. – Prashant Sable Nov 21 '19 at 09:53
  • @PrashantSable My Fragment call from outer environment which is not native, so I am not aware about its xml or IDs. – Dattu Hujare Nov 22 '19 at 05:47

2 Answers2

2

You can use android.R.id.content

Check out this answer so you can know why.

  • Thanks for solution, its working but my fragment is inside in view pager and view pager is having its parent fragment. So now it is replacing that parent fragment rather than view pager child. – Dattu Hujare Nov 22 '19 at 05:52
  • then the next logical step would be to try ravikwow's answer, getting the id of the parent view, rather than root view. good luck. – Elvedin Selimoski Nov 22 '19 at 15:28
1

If you want replace fragment from fragment, then you need get container id like this

((View)getView().getParent()).getId()
ravikwow
  • 111
  • 2
  • This solution works better for me (more reliable), just make sure both `view` and `parent` are not null before retrieving the id! – tonymanou Jun 10 '20 at 11:04