我的 Firestore 中有以下結構,我想讀取資料并將其存盤在 ArrayList 中,就像我有“amountArrayList”一樣,它將從 Firestore 的“transactions”欄位中讀取資料,我想從“中讀取所有“amount”欄位交易”欄位并制作它的陣列串列,以便我可以以串列方式顯示它。

我的代碼
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("transactions")) {
System.out.println(entry.getValue().toString());
}
}
輸出
[{transactionType=Credit, amount=3000, dateToStr=17/12/2021, timeToStr=08:06:10, description=}, {transactionType=Credit, amount=2000, dateToStr=17/12/2021, timeToStr=08 :06:50,描述=}]
uj5u.com熱心網友回復:
由于transactions是一個陣列欄位,因此您從中獲得的值entry.getValue()是一個List物件。由于 JSON 中的這些物件中的每一個都有屬性,因此它們Map<String, Object>在 Java 代碼中都將是一個。
列印金額的簡單方法如下:
List transactions = document.get("transactions");
for (Object transaction: transactions) {
Map values = (Map)transaction;
System.out.println(values.get("amount")
}
uj5u.com熱心網友回復:
雖然 Frank van Puffelen 的回答會很好地作業,但有一個解決方案,您可以將“交易”陣列直接映射到自定義物件串列中。假設您有一個如下所示的類宣告:
class User {
public String balance, email, firstname, lastname, password, username;
public List<Transaction> transactions;
public User(String balance, String email, String firstname, String lastname, String password, String username, List<Transaction> transactions) {
this.balance = balance;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.username = username;
this.transactions = transactions;
}
}
還有一個看起來像這樣:
class Transaction {
public String amount, dateToStr, description, timeToStr, transactionType;
public Transaction(String amount, String dateToStr, String description, String timeToStr, String transactionType) {
this.amount = amount;
this.dateToStr = dateToStr;
this.description = description;
this.timeToStr = timeToStr;
this.transactionType = transactionType;
}
}
要獲取串列,它將非常簡單:
docRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
List<Transaction> transactions = document.toObject(User.class).transactions;
List<String> amountArrayList = new ArrayList<>();
for(Transaction transaction : transactions) {
String amount = transaction.amount;
amountArrayList.add(amount);
}
// Do what you need to do with your amountArrayList
}
}
});
您可以在以下文章中閱讀更多資訊:
- 如何將物件陣列從 Cloud Firestore 映射到物件串列?。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/385226.html
標籤:爪哇 安卓 火力基地 谷歌云平台 谷歌云firestore
上一篇:在什么情況下會下載FirebaseFirestore資料庫?
下一篇:如何添加身份驗證自定義宣告
