如何從 Firebase Realtime 獲取特定值并收集所有這些值以向用戶顯示銷售串列 android studio 中所有孩子的總價值 - 使用 java
從 Firebase Realtime 獲取特定值并收集它們的值 android studio - 使用 java

public class SalesFragment extends Fragment {
TextView otherSalesValue, otherEarnsValue;
DatabaseReference databaseReference;
int sale;
String currentUserId;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_sales, container, false);
currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference("sales");
otherSalesValue = root.findViewById(R.id.other_sales_value);
otherEarnsValue = root.findViewById(R.id.other_earns_value);
databaseReference.child(currentUserId)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot booksSnapshot : uniqueKeySnapshot.child("total").getChildren()) {
String sales = booksSnapshot.getValue(String.class);
try {
sale = Integer.parseInt(sales);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
sale = sale;
otherEarnsValue.setText(String.valueOf(sale));
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return root;
}
}
uj5u.com熱心網友回復:
sales您讀取的節點下面有兩個動態子級別,因此您需要經過兩個嵌套回圈getChildren()才能獲得該total屬性。
databaseReference.child(currentUserId)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot dateSnapshot : userSnapshot.getChildren()) {
// ?? loop over all child nodes
long totalValue = dateSnapshot.child("total").getValue(Long.class);
// ?? get the total for this date
sale = sale totalValue; // ?? add the daily total to the sum
}
}
otherEarnsValue.setText(String.valueOf(sale));
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // ?? never ignore errors
}
});
請注意,如果您只需要每日總數的總和,那么讀取每個客戶端中的所有附加資料是非常浪費的。
考慮將運行總計存盤在資料庫的更高級別節點中(可能在 中/sales_total),并在您更新每日總計時更新它。像這樣將資料保存在多個位置在 NoSQL 資料庫中很常見,這也是它們的讀取操作擴展性如此之好的部分原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324779.html
