如何分离firestore监听器

Rap*_*des 8 android google-cloud-firestore

我是FireStore的新手.我创建了一个ListenerRegistration来更新我的Recycler View.我知道我的实现可能并不完美,但每次我的活动被破坏时,我的应用程序都会在此监听器内的行上引发错误.我不知道为什么,但是mt registration.remove()在destroy之前或者finish()活动之后都没有工作.有人可以帮忙吗?

public class MainActivity extends AppCompatActivity {

  private ListenerRegistration registration;
  private com.google.firebase.firestore.Query query;

  private void requestPacienteList(){

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    progress.setVisibility(View.VISIBLE);
    query = db.collection("Hospital");
    registration = query.addSnapshotListener(new EventListener<QuerySnapshot>() {

        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
            for(DocumentSnapshot documentSnapshot : documentSnapshots){

                if(documentSnapshot.get("nome").equals("Santa Clara")){

                    hospital = documentSnapshot.toObject(Hospital.class);
                    hospital.setHospitalDocumentKey(documentSnapshot.getId());
                    FirebaseFirestore db = FirebaseFirestore.getInstance();

                    db.collection("Hospital")
                            .document(hospital.getHospitalDocumentKey())
                            .collection("Pacientes")
                            .addSnapshotListener(new EventListener<QuerySnapshot>() {

                                 @Override
                                public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                                    homeModelList.clear();
                                    for(DocumentSnapshot documentSnapshot : documentSnapshots){

                                        final Paciente paciente = documentSnapshot.toObject(Paciente.class);
                                        paciente.setPacienteKey(documentSnapshot.getId());
                                        FirebaseFirestore db = FirebaseFirestore.getInstance();
                                        db.collection("Pessoa")
                                                .document(paciente.getProfissionalResponsavel())
                                                .addSnapshotListener(new EventListener<DocumentSnapshot>() {

                                                    @Override
                                                    public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {

                                                        Profissional profissional = documentSnapshot.toObject(Profissional.class);
                                                        int[] covers = new int[]{R.drawable.ic_person_black};
                                                        HomeModel p = new HomeModel(paciente.getNome()+" "+paciente.getSobrenome(),paciente.getBox(),paciente.getLeito(),
                                                        covers[0],profissional.getNome()+ " "+profissional.getSobrenome(),paciente.getPacienteKey());
                                                        homeModelList.add(p);
                                                        homeAdapter.notifyDataSetChanged();
                                                        prepareListaPacientes();
                                                    }
                                        });
                                    }
                                }
                            });
                    }
            }
        }
    });

    switch (id){

        case R.id.logout:

            if(FirebaseAuth.getInstance().getCurrentUser()!=null)
                FirebaseAuth.getInstance().signOut();

            Intent it = new Intent(HomeActivity.this, MainActivity.class);
            startActivity(it);

            if(registration!=null)
                registration.remove();

            finish();

            drawerLayout.closeDrawers();
            break;
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

我的onDestroy方法:

@Override
protected void onDestroy() {
    super.onDestroy();
    registration.remove();
}
Run Code Online (Sandbox Code Playgroud)

当我删除此如果:

if(FirebaseAuth.getInstance().getCurrentUser()!=null)
    FirebaseAuth.getInstance().signOut();
Run Code Online (Sandbox Code Playgroud)

我的问题消失了.但如果我不这样做,我会收到以下错误:

public class MainActivity extends AppCompatActivity {

  private ListenerRegistration registration;
  private com.google.firebase.firestore.Query query;

  private void requestPacienteList(){

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    progress.setVisibility(View.VISIBLE);
    query = db.collection("Hospital");
    registration = query.addSnapshotListener(new EventListener<QuerySnapshot>() {

        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
            for(DocumentSnapshot documentSnapshot : documentSnapshots){

                if(documentSnapshot.get("nome").equals("Santa Clara")){

                    hospital = documentSnapshot.toObject(Hospital.class);
                    hospital.setHospitalDocumentKey(documentSnapshot.getId());
                    FirebaseFirestore db = FirebaseFirestore.getInstance();

                    db.collection("Hospital")
                            .document(hospital.getHospitalDocumentKey())
                            .collection("Pacientes")
                            .addSnapshotListener(new EventListener<QuerySnapshot>() {

                                 @Override
                                public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                                    homeModelList.clear();
                                    for(DocumentSnapshot documentSnapshot : documentSnapshots){

                                        final Paciente paciente = documentSnapshot.toObject(Paciente.class);
                                        paciente.setPacienteKey(documentSnapshot.getId());
                                        FirebaseFirestore db = FirebaseFirestore.getInstance();
                                        db.collection("Pessoa")
                                                .document(paciente.getProfissionalResponsavel())
                                                .addSnapshotListener(new EventListener<DocumentSnapshot>() {

                                                    @Override
                                                    public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {

                                                        Profissional profissional = documentSnapshot.toObject(Profissional.class);
                                                        int[] covers = new int[]{R.drawable.ic_person_black};
                                                        HomeModel p = new HomeModel(paciente.getNome()+" "+paciente.getSobrenome(),paciente.getBox(),paciente.getLeito(),
                                                        covers[0],profissional.getNome()+ " "+profissional.getSobrenome(),paciente.getPacienteKey());
                                                        homeModelList.add(p);
                                                        homeAdapter.notifyDataSetChanged();
                                                        prepareListaPacientes();
                                                    }
                                        });
                                    }
                                }
                            });
                    }
            }
        }
    });

    switch (id){

        case R.id.logout:

            if(FirebaseAuth.getInstance().getCurrentUser()!=null)
                FirebaseAuth.getInstance().signOut();

            Intent it = new Intent(HomeActivity.this, MainActivity.class);
            startActivity(it);

            if(registration!=null)
                registration.remove();

            finish();

            drawerLayout.closeDrawers();
            break;
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

Fra*_*len 19

当您使用时addSnapshotListener,附加一个被调用以进行任何更改的侦听器.显然你必须在活动被破坏之前分离那些听众.另一种方法是activity您的电话添加到addSnapshotListener:

 db.collection("Pessoa").document(paciente.getProfissionalResponsavel())
   .addSnapshotListener(MainActivity.this, new EventListener<DocumentSnapshot>() {
Run Code Online (Sandbox Code Playgroud)

您需要更新MainActivity.this以匹配您的代码.

通过传入活动,Firestore可以在活动停止时自动清理侦听器.

另一种替代方法是用它来get()记录那些嵌套的文档,它只读取文档一次.因为它只读一次,所以没有听众清理.


Gee*_*kur 7

使用registration.remove();的停止收听变化

Query query = db.collection("cities");
ListenerRegistration registration = query.addSnapshotListener(
        new EventListener<QuerySnapshot>() {
            // ...
        });

// ...

// Stop listening to changes
registration.remove();
Run Code Online (Sandbox Code Playgroud)

查看有关此内容的更多信息:https : //firebase.google.com/docs/firestore/query-data/listen#detach_a_listener