Each Fragment in my application has their own set of continuous Firebase listeners. These become unnecessary once the active Fragment has changed, however, the listeners continue in the background. Besides that, these old listeners may trigger View updates for the previous Fragment, which may then crash the application. So, I'd like to be tidy and clean up the listeners once the Fragment changes. I do not know how, but I have an alternative solution and I was curious about your thoughts and suggestions.
The listener functions are called in the Fragments onCreate
, for example:
fuSetListener();
These functions retrieve and save the data in global variables.
In the onDataChange
of the Firebase listener I perform this if-statement to check if the listener should be removed:
if(getActivity()==null){
reference.removeEventListener(this);
} else {
// Perform necessary onDataChange actions
}
So the question arises, does getActivity()
only return null
in case the Fragment has changed? Or may getActivity()
return null
without changing the Fragment and mess up my Fragments purpose?
I have applied this method a couple of times and do not run into trouble yet, but I wanted to check with you before proceeding.
You need to remove the listener accordingly to the
life-cycle
of your fragment.If you have added the listener in
onStart
you have to remove it inonStop
. If you have added the listener inonResume
you have to remove it inonPause
. If you have added the listener inonCreate
you have to remove it inonDestroy
. But rememberonDestroy
is not always called.Hope it helps.