[英]After getting all documents in collection can't add field to ArrayList, Android Studio, Java, Firebase Firestore
[英]Firebase Cloud Firestore: Query isn't updating ArrayList in Android
我正在使用以下查詢:
db.collection("Example")
.whereEqualTo("UserId", currentUser.getUid())
.orderBy("timestamp", Query.Direction.ASCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for (QueryDocumentSnapshot document : task.getResult()){
Log.i(TAG, "onComplete: " + document.get("UserId") + " => " + document.get("userText"));
userIdArrayList.add(document.get("UserId").toString());
userTextArrayList.add(document.get("userText").toString());
}
}else{
Log.i(TAG, "onComplete: Error getting documents", task.getException());
}
}
});
當查詢遍歷結果時,我希望它將結果添加到數組中。 但是,當我運行代碼並嘗試打印數組列表的內容時,盡管我查看了userTextArrayList.get(0);
但我還是收到了IndexOutOfBounds
異常userTextArrayList.get(0);
其中應該包含一個結果。 我添加了一行Log.i
來檢查代碼是否成功運行,我可以在 Logcat 中看到正在從數據庫中提取數據。 出於某種原因,此代碼未將結果添加到 ArrayList。
我不知道還有什么可以嘗試的,而且我無法在文檔中找到任何可以幫助我解決可能出錯的地方。
如果提供答案太麻煩,請隨時向我指出可以幫助解決問題的文檔。 我感謝任何人可以提供的任何指導。
謝謝!
編輯:我在以下代碼行中收到錯誤消息:
userIdArrayList.add(document.get("UserId").toString());
userTextArrayList.add(document.get("userText").toString())
出於某種原因,這些行沒有將數據添加到數組中,當我稍后在代碼中嘗試打印數組時(即Log.i(TAG, "User Text => userTextArrayList.get(0).toString());
),我收到了IndexOutOfBounds
錯誤信息 - 盡管上面的代碼向 ArrayLists 添加了數據,但顯然 ArrayList 不包含數據。
您需要了解此查詢是異步的,並且當您執行此日志語句Log.i(TAG, "User Text => userTextArrayList.get(0).toString());
時,結果可能尚未添加到userTextArrayList
Log.i(TAG, "User Text => userTextArrayList.get(0).toString());
此日志語句需要在onComplete()
,如下所示,才能使其工作:
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.i(TAG, "onComplete: " + document.get("UserId") + " => " + document.get("userText"));
userIdArrayList.add(document.get("UserId").toString());
userTextArrayList.add(document.get("userText").toString());
}
yourButton.setEnabled(true);
} else {
Log.i(TAG, "onComplete: Error getting documents", task.getException());
yourButton.setEnabled(false);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.