Good morning, I've been programming on Android for a few weeks and I'm having certain problems with the use of getFragmentManager
.
I have read post about the termination of activities and this is what I have come up with:
Quote Answer Stack Over Flow English 1
Also onDestroy() is not a destructor. It doesn't actually destroy the object, it's just a method that returns a certain state.
in addition to this:
Quote Answer Stack Over Flow English 2
Consider then that your application will be in the background and then die. When you come back Android will remember that you had Fragments, for example A, B and C and the manager will recreate them and then add them.
I call the method 2 times from one of my activities, and the second time (after doing a getActivity.finish()
, recreating the activity and returning to the method from the previous fragment), it points to null.
The point of failure is:
private BroadcastReceiver estadoIAReceiver = new BroadcastReceiver() {
//Cuando cambia el estado de indoor atlas actualizo la interfaz con sus propiedades
@Override
public void onReceive(Context context, Intent intent) {
Log.i("VFragment", "Cambio estado IA");
//Ejecutar metodo de un fragment desde una actividad
infoF = (InformacionFragment) getFragmentManager().findFragmentById(R.id.posicionamiento_layout); // <<--- AQUI!!!
infoF.actualizaInfoEstadoIA();
infoF.onResume();
}
};
and infoF
is what it givesnull
infoF = (InformacionFragment) getFragmentManager().findFragmentById(R.id.posicionamiento_layout);
this brings me backnull
I've been debugging the app and re-creating activities and fragments
it's correct, so it shouldn't point to null
.
My question is:
With what I read, I have intuited that it is trying to point to the old fragment
one (1 time executed), since finish
() does not really delete 100% Activity
(and I assume it fragments
does not either). How could I fix it?
I finally solved my problem. Apparently, when doing a finish() you don't completely destroy the activity, but rather some information is saved in savedInstanceState, and therefore when trying to point to the Fragment, it returns null.
The solution is the next:
Just create a new variable of type Bundle as a global variable:
SaveData Bundle;
To store the savedInstanceState information
savedData = savedInstanceState;
And check that said variable is not null before calling getFragmentManager
if (DataSaved != null) infoF = (FragmentInformation) getFragmentManager().findFragmentById(R.id.positioning_layout);
When calling , the Activity is completely destroyed, but first the onSaveInstanceState()
finish()
method is called (if it is implemented) , which is where you can save desired values, as an example it saves the user value:in this case it can also be used to know if an instance previously existed, and also the saved value is obtained through onSaveInstanceState() , example: