Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);}
like image 590
NightOwl Avatar asked Oct 30 '22 10:10

NightOwl


1 Answers

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

like image 131
Frank van Puffelen Avatar answered Nov 13 '22 22:11

Frank van Puffelen