I'm trying to develop an application that contains only one Activity and two Fragments . Each Fragment can call the interface method implemented by the Activity :

 @Override public void onFragmentRequest(final String fragmentTag) { new Thread(new Runnable() { @Override public void run() { try { // симулируем работу с сетью Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { Fragment fragment = getSupportFragmentManager() .findFragmentByTag(fragmentTag); if(fragment == null) Log.d(TAG, "fragment is null"); else { if(fragment instanceof OnFragmentResponse) ((OnFragmentResponse) fragment).onFragmentResponse(); } } }); } }).start(); } 

But the problem is that after rotating the screen (changing the configuration) after calling onFragmentRequest , getSupportFragmentManager().findFragmentByTag(fragmentTag) returns null

I replace all the fragments and add them to the back stack, and after all this I call the commit method, as well as manager.executePendingTransactions() , but this does not solve the problem

Logs before or without screen rotation:

 02-07 16:39:12.202 29750-29750/com.testfrag3 D/MainActivity: onFragmentRequest: fragmentTag = NewsFragment 02-07 16:39:12.203 29750-29750/com.testfrag3 D/MainActivity: getSupportFragmentManager.entryCount = 1 02-07 16:39:12.203 29750-29750/com.testfrag3 D/NewsFragment: onFragmentResponse success 

Logs, when onFragmentRequest was called and a turnaround occurred:

 02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: onFragmentRequest: fragmentTag = NewsFragment 02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: getSupportFragmentManager.entryCount = 1 02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: fragment is null 
  • Looks like the code is called in the already "destroyed" activations and there is nothing in it, that's Null. Try to transfer the emulation of work with the network to Singlton and from it at the right time to call the actviti method, the link to which activations will be transferred to singleton at start, and removed at stop, for example , YuriySPb
  • I also think that the reason is that I call getSupportFragmentManager from the destroyed activation, but then somehow it doesn’t fit in my head: the activation is destroyed, but its context is not, and you can call its methods. I also thought that runOnUiThread will be called from the newly created activation, but it was not there) - Trancer
  • I like the singleton version. Just initially did not want to keep anything in the background. Activity was supposed to act as a controller. Now I think for this to make a separate class AsyncTask based on the retain fragment, to which the fragments and the activation itself will turn when it is necessary to receive or send data from the network. - Trancer
  • For those who will look for an answer to this question: github.com/alexjlockwood/adp-worker-fragments - Trancer

0