I've got an activity and I'm using FragmentStateAdapter class (ViewPager2) to slide between two fragments, similar like in https://developer.android.com/training/animation/screen-slide-2.
My current problem is, that when I try to access onto view elements of second fragment in my activity:
TextView textViewOfFragmentB = (TextView) fragmentB.getView().findViewById(R.id.exampleTextViewOfFragmentB);
I'm receving:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
When I try this with the first fragment (of that slider) it works. Probably because it's the first fragment and visible initially?
What possibilities do I have to acces onto view elements of both fragments,event if one of them is not visible/created?
My use case is something like: I have two fragments. The one is showing food and the other drinks. The fragments shall be slideable, so only one category is shown on the screen (Similiar like: https://developer.android.com/training/animation/anim_page_transformer_zoomout.mp4). With a service I'm receiving external data for both categories in my MainActivity. So I already have all data I need inside MainActivity. And this data I want to split onto both fragments and display them, like Pizza : 4 $, and on the other fragment Cocktail: 5 $