Vanessa Tan
Vanessa Tan

Reputation: 97

Where to set Firebase AddValueEventListener in a fragment?

I am creating an android app with fragments that pulls data from Firebase.

Currently, I have set my addValueEventListener inside the onStart() method, which is able to pull data from Firebase the first time a fragment is accessed, but when I change to view other fragments in the app and return to the original fragment, the Firebase data disappears until I rotate the screen.

Where should I place my AddValueEventListener method to get around this problem?

Upvotes: 2

Views: 2595

Answers (2)

Vinoth
Vinoth

Reputation: 9734

Just add the addValueEventListener inside the onCreateView() method of Fragment. Then store your values into ArrayList or any other collection classes. Just show your values from this ArrayList into Fragment.

Notice : You can't store your values outside the onDataChange() method of addValueEventListener. So just create one method with arraylist param and pass the values from onDataChange() method to that newly created method. By this way your data should not be null and you won't get NullPointerException

See this doc for more information.

Upvotes: 0

A.Zidan
A.Zidan

Reputation: 563

Short answer: add it to the onResume method and remove it in onPause method.

Long answer: Fragments are managed by the FragmentManager, which in most cases keeps an instance of the fragment so that it doesn't need to create a new fragment every time you want it to be shown. So the methods onCreate, onCreateView, onStart will be called once on the creation of the fragment or on configuration changing, i.e. screen rotation.

On the other hand, onResume method will be called every time you the fragment is taking the focus so adding the addValueEventListener will always be called. However, this will lead to add multiple value even listener so it would be a good practice to removeEventListener in onPause method.

See: https://developer.android.com/guide/components/fragments.html

Upvotes: 5

Related Questions