how to I find the correct findFragmentById to accesss the TextView?

24 Views Asked by At

I have an activity which consists of 2 buttons and a fragment container. I have set the fragment container so it by defaults loads the first fragment. Then I have 2 fragments which both have a TextView each. I am trying to set its text through the activity, and I saw that I need to access the fragment container/layout first before I can update its text. However, I have tried and I kept getting null pointer exceptions. I messed around a bit and put the ID of my fragment container view of my activity, it provides me a result but I could not access the textView as when I tried to change its text, it says it is null.

Can someone help me with this? Here is the chunk of code from the main activity page.

Activity

FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.myFragmentContainer, FirstFragment.class, null)
                .setReorderingAllowed(true)
                .commit();

FirstFragment testFragment = (FirstFragment)getSupportFragmentManager().findFragmentById(R.id.myFragmentContainer);
        FirstFragment getFragment = (FirstFragment) testFragment.getChildFragmentManager().findFragmentById(R.id.myFragment1ID);

        getFragment.updateTextView("Test");

My fragment container view ID from my main page is "myFragmentContainer" My fragment layout which contains the TextView is "myFragment1ID"

I have tried inserting multiple different Ids and trying it with findFragmentByTag instead of ID but it still doesnt work for me.

0

There are 0 best solutions below