There is an activity in which 2 fragments constantly alternate, after the fragment replacement code, the code in which the view elements of this fragment are filled occurs, but nullPointException is thrown because the onCreateView in the fragment has not yet been called. What is the problem, how can I synchronize these actions?

Everything happens here, the fragment still does not have time to appear on the screen, as the call to the setFocusPlayer method occurs, which it tries to fill the view in the fragment

private void setTalkScreen() { replaceFragment(playersTalkFragment); if (world.isPlayerInGame(0)) { setFocusPlayer(0); } else { setFocusPlayer(world.nextPlayer(World.NONE)); } } private void replaceFragment(Fragment newFragment) { FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); transaction.replace(R.id.fragment_container, newFragment); transaction.commit(); Log.d(LOGIC, "GameActivity -> replaceFragment"); } 
  • Code. Show the code. In general, it is not clear what and when you do. - Rostislav Dugin
  • @ RostislavDugin code added - Pasha Doncov
  • And when do you call this code? From where do you get fragmentManager ? - Rostislav Dugin
  • @ RostislavDugin FragmentManager is saved in onCreate, the code is called after onResume, and then several times during the session - Pasha Doncov
  • And on which line does the NPE fly out? - Rostislav Dugin

2 answers 2

Add a callback to the Fragment to the onAttach method:

 class TheFragment extends Fragment { public interface ActivityCallback { void onAttach(); } ... @Override public void onAttach() { ... ((ActivityCallback) activity).onAttach(); } } class TheActivity extends AppCompatActivity implements TheFragment.ActivityCallback { @Override onAttach() { //Делаете ваши действия с фрагментом, //он уже готов. К работе, я имею ввиду :) } ... } 
  • Thanks, works) - Pasha Doncov

I advise you to try either @Rostislav or try instead commit using commitNow

  • Tried, did not help - Pasha Doncov