我正试图从Firestore数据库中获取帐户数据,但是当我在文档上调用get()时,添加的OnSuccessListener和OnFailureListener似乎没有调用它们各自的方法。
我尝试使用直接的DocumentReference切换出collectionReference.document(),但是遇到了同样的问题。
private List<Account> accounts = new LinkedList<>();
private void fetchAccounts(String[] accountNames) {
Log.d(TAG, "fetchAccounts: fetching accounts...");
CollectionReference collectionReference =
FirebaseFirestore.getInstance().collection("accounts");
for (String name : accountNames) {
collectionReference.document(name).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
Log.d(TAG, "onSuccess: account fetched");
accounts.add(documentSnapshot.toObject(Account.class));
} else {
Log.d(TAG, "onSuccess: document doesn't exist");
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG, "onFailure: something went wrong");
}
});
}
Log.d(TAG, "fetchAccounts: " + accounts.get(0).getType());
}
这是我的帐户类别:
public class Account {
private int balance;
private AccountType type;
private String accountNumber, registrationNumber, owner;
public Account() {
}
public int getBalance() {
return balance;
}
public AccountType getType() {
return type;
}
public String getAccountNumber() {
return accountNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public String getOwner() {
return owner;
}
}
AccountType是一个简单的枚举。
应该成功或者将帐户添加到我的列表中,或者失败并给我某种日志输出,但是当我调用列表中的元素时,它似乎跳过了这一部分而抛出了IndexOutOfBoundsException。