2017-11-25 268 views
0

我公司的FireStore結構看起來是這樣的:公司的FireStore:從收集查詢所有文檔

-(coll)users 
    -(doc)uniqueID 
    name 
    email 
    (coll)clients 
     -(doc)uniqueID 
     clientName 
     clientEmail 

我想實現如下:

  1. 通過FirebaseUI驗證流程的用戶登錄
  2. 如果用戶(從Auth恢復的uid)在firestore db中不存在,我創建一個由他的用戶名命名的文檔
  3. 一旦我有了uid,我運行一個查詢來加載clie nts收集,以便使用RecyclerView將它們顯示在列表中(如果收集爲空,則用戶尚未創建任何客戶端,但我顯示空列表屏幕)

我試圖使用下面的代碼爲每documentation

clientsCollection = db.collection(FIRESTORE_COLLECTION_USERS) 
      .document(mUid) 
      .collection(FIRESTORE_COLLECTION_CLIENTS); 

    clientsCollection 
      .get() 
      .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { 
       @Override 
       public void onComplete(@NonNull Task<QuerySnapshot> task) { 
        if (task.isSuccessful()){ 
         for (DocumentSnapshot document: task.getResult()){ 
          Log.d(LOG_TAG, document.getId() + " => " + document.getData()); 
         } 
        } else { 
         Log.d(LOG_TAG, "error getting documents: ", task.getException()); 
        } 
       } 
      }); 

我得到以下RuntimeException

java.lang.NullPointerException: Provided document path must not be null. 

我得到這個即使客戶端收集退出一些文檔它由獨特的用戶名命名。

感謝您的任何線索,你可以給我! :)

回答

0

當您運行第一個語句時,錯誤消息指示mUidnull。很可能這意味着您在用戶登錄之前運行此代碼。

確保您只在用戶登錄後調用此代碼,例如,從AuthStateListener.onAuthStateChanged()

FirebaseAuth.getInstance().addAuthStateListener(new AuthStateListener() { 
    public void onAuthStateChanged(FirebaseAuth auth) { 
     FirebaseUser user = firebaseAuth.getCurrentUser(); 
     if (user != null) { 
      clientsCollection = db.collection(FIRESTORE_COLLECTION_USERS) 
        .document(user.getUid()) 
        .collection(FIRESTORE_COLLECTION_CLIENTS); 

      clientsCollection 
        .get() 
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { 
         @Override 
         public void onComplete(@NonNull Task<QuerySnapshot> task) { 
          if (task.isSuccessful()){ 
           for (DocumentSnapshot document: task.getResult()){ 
            Log.d(LOG_TAG, document.getId() + " => " + document.getData()); 
           } 
          } else { 
           Log.d(LOG_TAG, "error getting documents: ", task.getException()); 
          } 
         } 
     } 
    } 
})