簡體   English   中英

Firestore - 為什么要檢查 DocumentSnapshot 是否為空並且調用是否存在?

[英]Firestore - Why check if DocumentSnapshot is not null AND call exists?

Firestore文檔中查看此代碼示例:

DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null && document.exists()) {
                Log.d(TAG, "DocumentSnapshot data: " + document.getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
           Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

https://firebase.google.com/docs/firestore/query-data/get-data

為什么要檢查document != null 如果我正確閱讀了源代碼(初學者), exists方法會在內部檢查無效性。

成功完成的任務永遠不會為DocumentSnapshot傳遞null 如果請求的文檔不存在,您將獲得一個空快照。 這意味着:

  • 調用document.exists()返回 false
  • 調用document.getData()拋出異常

所以確實沒有理由在調用document.exists()之前檢查document != null

如果執行以下語句:

document != null

它將被評估為false ,這意味着您的tasknull並且將打印出以下消息:

Log.d(TAG, "No such document");

但是,如果您在task對象上調用方法(例如 toString()),它將拋出以下錯誤:

java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.

此消息明確告訴您使用exists()方法而不是檢查無效性。

關於使用how to get a document方法的官方文檔說:

注意:如果docRef引用的位置沒有文檔,則生成的文檔將為空。

如果documentSnapshotnullable您應該執行以下操作:

if (documentSnapshot != null) {
    if (documentSnapshot.exists()) {
         //exists
    } else {
         //doesn't exist
    }
} 

此類錯誤的另一個直接解決方法是


DocumentSnapshot documentSnapshot = task.getResult();

 assert documentSnapshot != null;
 if (documentSnapshot.exists()) {

      //Your operation e.g
     ArrayList<String> obj= (ArrayList<String>) documentSnapshot.get("documentObject");
     String s = Objects.requireNonNull(obj).toString();
     Toast.makeText(context, "THIS WORKS "+ s, Toast.LENGTH_SHORT).show();

  } else {
     //Another operation
   Toast.makeText(context, "DOES NOT EXIST", Toast.LENGTH_SHORT).show();
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM