I am creating an application of sale purchase I want to retrieve all the profit of sale mobiles and Sum the values to obtain the total earning.
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<Float> list = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
list.add(Float.valueOf(Float.parseFloat(ds.child("profit").getValue().toString())));
double sum = 0.0;
for (Float d : list) {
double floatValue = (double) d.floatValue();
Double.isNaN(floatValue);
sum += floatValue;
}
Toast.makeText(RecordsActivity.this, "Earning = " + sum, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(RecordsActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
For starters I would suggest that you send profits to the database as ints. Then you can find the total sum of the figures under the nodes profits in a data snapshot as shown below
@Override
public void onDataChange(@NonNull DataSnapshot
dataSnapshot) {
int sum=0;
for (DataSnapshot ds1:dataSnapshot.getChildren()){
int a=ds1.child("profit").getValue(Integer.class);
sum+=b;
int i = sum;
String value = String.valueOf(i);
Toast.makeText(RecordsActivity.this, value,
Toast .LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.