我在这里有一个像这样的数据库结构。
我的目标是获得两个金额12000和15000的总和,这将是27000 ..但是我试图使用的代码给了我一个像 null1200015000 的值。这是代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mystatement);
listview = (ListView) findViewById(R.id.listview);
textView4 = (TextView) findViewById(R.id.textView4);
dref = FirebaseDatabase.getInstance().getReference();
DatabaseReference dref = FirebaseDatabase.getInstance().getReference();
dref = dref.child("Expenditure");
dref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
//Adding it to a stringString expenses = "Amount: "+dogExpenditure.getAmount()+"\nReason for Use: "+dogExpenditure.getItem()+"\n\n";
String amount = dogExpenditure.getAmount();
textView4.setText(amount);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
任何有想法如何实现这一点的人? 这是我的DogExpenditure类:
public class DogExpenditure {
private String amount;
private String item;
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
答案 0 :(得分:0)
全球定义DogExpenditure dogExpenditure并使用此
dref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
//Adding it to a stringString expenses = "Amount: "+dogExpenditure.getAmount()+"\nReason for Use: "+dogExpenditure.getItem()+"\n\n";
}
if(dogExpenditure.size()>0){
int amt=0;
for(int i=0;i<dogExpenditure.size();i++){
amt =amt+Integet.parseInt(dogExpenditure.get(i).getAmount())
}
textView4.setText(""+amt);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
答案 1 :(得分:0)
如果我理解正确,那应该很简单:
首先,将amount
中的DogExpenditure
更改为double
或int
:
public class DogExpenditure {
private int amount;
...
public int getAmount() {
return amount;
}
...
}
然后在onDataChange()
内,只需按每个amount
值递增它。像这样:
public void onDataChange(DataSnapshot snapshot) {
int totalAmount = 0;
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
totalAmount += dogExpenditure.getAmount();
}
textView4.setText(totalAmount.toString());
}