android studio firestore 查询快照异常(使用 whereEqualTo)

android studio firestore querysnapshot exception(using whereEqualTo)

所以代码可能看起来很乱,这是一个设备报告页面,我想做的是使用微调器,以便用户可以选择他们想要检查的状态(在字段名称“状态”中),这是微调器是什么样的,4 状态,但在 firestore 中现在只存在一个

    <string-array name="reportst">

        <item>待處理</item>
        <item>處理中</item>
        <item>待驗收</item>
        <item>已完成</item> //THIS IS THE ONE EXIST NOW

    </string-array>

目前只有一个状态字段为“状态”的文档在“已完成”,表示已完成, 但我希望用户检查另一个,即使它不存在(显示空列表视图,不崩溃)

我的代码写在下面

 @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        spinvar = parent.getItemAtPosition(position).toString();

        DocumentReference docRef2 = firebaseFirestore.collection("users").document(userID);

        docRef2.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        Log.d("TAG", "DocumentSnapshot data: " + document.getData());
                        recID = document.getString("recID");
                        firebaseFirestore.collection("equipmentReport").whereEqualTo("recID",recID).whereEqualTo("狀態",spinvar).orderBy("createdAt", Query.Direction.DESCENDING).addSnapshotListener((documentSnapshots, error) -> {
                            ar.clear();

                            **for (DocumentSnapshot snapshot : documentSnapshots){**//THE ERROR
                                if(snapshot != null){
                                    if(snapshot.exists()){
                                        idlv = snapshot.getId();
                                        urll = snapshot.getString("照片");

                                        if (snapshot.getDate("createdAt") != null) {
                                            //  Date timestamp = snapshot.getDate("createdAt");
                                            //Do what you need to do with this timestamp
                                            Timestamp timestamp = (Timestamp) snapshot.getData().get("createdAt");
                                            Date date = timestamp.toDate();
                                            date2 = date.toString();
                                        }


                                        ar.add(new itemAnnounce(R.drawable.pp, snapshot.getString("報修地點"),"反映於 "+date2,"事由:"+snapshot.getString("申報事由"),"狀態:"+snapshot.getString("狀態"),idlv,url));
                                    }else{

                                    }

                                }else{

                                }



                            }
                            adapterAnnounce adapterAnnounce = new adapterAnnounce(getApplicationContext(), R.layout.list_row_announce, ar);
                            adapterAnnounce.notifyDataSetChanged();
                            lv1.setAdapter(adapterAnnounce);

                            lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Object selectedObj =adapterAnnounce.getItem(position).getId();// this will get you selected obj of itemAnnounce
                                    String obj = (String)selectedObj.toString();
                                    DocumentReference docRef = firebaseFirestore.collection("equipmentReport").document(obj);
                                    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                        @Override
                                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                            if (task.isSuccessful()) {
                                                DocumentSnapshot document = task.getResult();
                                                if (document.exists()) {
                                                    Log.d("TAG", "DocumentSnapshot data: " + document.getData());
                                                    String stat = document.getString("狀態");
                                                    if(stat.equals("待驗收")){
                                                        Intent i = new Intent(MyEQreport.this,EQreportRate.class);
                                                        i.putExtra("eqrId",obj);
                                                        startActivity(i);
                                                    }else{

                                                    }

                                                } else {
                                                    Log.d("TAG", "No such document");
                                                }
                                            } else {
                                                Log.d("TAG", "get failed with ", task.getException());
                                            }

                                        }
                                    });

                                }
                            });
                        });
                    } else {
                        Log.d("TAG", "No such document");
                    }
                } else {
                    Log.d("TAG", "get failed with ", task.getException());
                }
            }
        });
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

错误是

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.districtapp, PID: 5916
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator com.google.firebase.firestore.QuerySnapshot.iterator()' on a null object reference
        at com.example.districtapp.MyEQreport.lambda$onComplete[=13=]$MyEQreport(MyEQreport.java:167)
        at com.example.districtapp.-$$Lambda$MyEQreport$hc9R1wp67pt9ujCkUwXliV_GHMs.onEvent(Unknown Source:4)
        at com.google.firebase.firestore.Query.lambda$addSnapshotListenerInternal$Query(Query.java:1126)
        at com.google.firebase.firestore.-$$Lambda$Query$JWhMgzcsIac1Z-exZj1pTDRisJg.onEvent(Unknown Source:6)
        at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent[=13=]$AsyncEventListener(AsyncEventListener.java:42)
        at com.google.firebase.firestore.core.-$$Lambda$AsyncEventListener$DNkggu2LY54oguDvcp-QtRg6Sfg.run(Unknown Source:6)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

我知道它需要一些快照异常,但它根本不起作用

null 检查移动到 documentSnapshots:

if(documentSnapshots != null){
  for (DocumentSnapshot snapshot : documentSnapshots) {
    if(snapshot.exists()){
      idlv = snapshot.getId();
      urll = snapshot.getString("照片");

      if (snapshot.getDate("createdAt") != null) {
        // Date timestamp = snapshot.getDate("createdAt");
        //Do what you need to do with this timestamp
        Timestamp timestamp = (Timestamp) snapshot.getData().get("createdAt");
        Date date = timestamp.toDate();
        date2 = date.toString();
      }
      
      ar.add(new itemAnnounce(R.drawable.pp, snapshot.getString("報修地點"),"反映於 "+date2,"事由:"+snapshot.getString("申報事由"),"狀態:"+snapshot.getString("狀態"),idlv,url));
    } else {
      
    }
  }
} else {

}