NightOwl
NightOwl

Reputation: 71

Firebase is Calling onChildAdded twice

I am calling OnChildAdded method inside SearchTextView OnQueryListener which searches and Display Records in Dialog using OnChildAdded method. But when I run the code the OnChildAdded method seems to call inner code twice as the dialog Prompt twice and same for Log Statements too.

Here is the Code of the method:

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
  mSearchQuery = query.trim();              
  mDatabaseReference.orderByChild("name").startAt(mSearchQuery).addChildEventListener(new ChildEventListener() {
    @Override
      public void onChildAdded(DataSnapshot dataSnapshot, String s) {

        student = dataSnapshot.getValue(Student.class);
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        EnrollOperationFragment enrollOperationFragment =  EnrollOperationFragment.newInstance(student.getName(),student.getId());
        enrollOperationFragment.show(fragmentManager,ENROLL_OPERATION);}

Upvotes: 5

Views: 2766

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

onChildAdded will be called for each child node matching your query. But also note that you're adding a new child listener each time the user submits the search text. So if they submit twice, you have two listeners and your onChildAdded will get called twice for each child (once for each listener). Then when they submit a search again, it'll add a third listener. And so on.

The solution is to detach the previous listener before attaching a new one. See the documentation for detaching listeners. Or use the code from her for inspiration: How stop Listening to firebase location in android

Upvotes: 2

Related Questions