Home > Software engineering >  How to get a sum of all values from a node in Firebase? Error
How to get a sum of all values from a node in Firebase? Error

Time:05-13

tell me, please: what is my mistake? I'm trying to apply your example, but I can't get the summation result. I want to add up all the prices and display them in TextView. I will be grateful for the help, I'm new to this. enter image description here

MainActivity package com.example.testkorzne;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.EventListener;

public class MainActivity extends AppCompatActivity implements ValueEventListener{
    private EditText edName, edPrice;
    private DatabaseReference mDataBase;
    private String USER_KEY = "User";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int total = 0;
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    String amount = ds.child("price").getValue(String.class);
                    int value = ds.getValue(Integer.class);
                    total =  value;
                }
                Log.d("TAG", String.valueOf(total)   " Rs.");

                TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
                quantityTextView.setText(""   total);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };
        mDataBase.addValueEventListener(this);
    }

    private void init() {
        edName = findViewById(R.id.edName);
        edPrice = findViewById(R.id.edPrice);
        mDataBase = FirebaseDatabase.getInstance().getReference(USER_KEY);
    }

    public void onClickSave(View view) {
        String id = mDataBase.getKey();
        String name = edName.getText().toString();
        String price = edPrice.getText().toString();
        User newUser = new User(id, name, price);
        if (!TextUtils.isEmpty(name))
        {
            mDataBase.push().setValue(newUser);
        } else {
            Toast.makeText(this, "Warning Not Text", Toast.LENGTH_LONG).show();
        }
    }
    public void onClickRead(View view) {

    }

    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {

    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
}

User Class package com.example.testkorzne;

public class User {
    public String id;
    public String name;
    public String price;

    public User() {

    }

    public User(String id, String name, String price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

}

xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@ id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:onClick="onClickSave"
        android:text="Save"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.312"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/edPrice" />

    <Button
        android:id="@ id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:onClick="onClickRead"
        android:text="Read"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.312"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/button" />

    <EditText
        android:id="@ id/edName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="76dp"
        android:ems="10"
        android:hint="NAME"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="TouchTargetSizeCheck" />

    <EditText
        android:id="@ id/edPrice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="PRICE"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.502"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/edName"
        tools:ignore="TouchTargetSizeCheck" />

    <TextView
        android:id="@ id/quantity_text_view"
        android:layout_width="124dp"
        android:layout_height="121dp"
        android:layout_marginStart="224dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/button2" />

</androidx.constraintlayout.widget.ConstraintLayout>

CodePudding user response:

To get the sum of all price fields that exist under each child in the User node, please use the following lines of code:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = db.child("User");
userRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            int sum = 0;
            for (DataSnapshot ds : task.getResult().getChildren()) {
                String price = ds.child("price").getValue(String.class);
                sum  = Integer.valueOf(price);
            }
            Log.d("TAG", "sum: "   sum);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

And the result in the logcat will be:

sum: 200

Please also note to store the prices as numbers and not strings, case in which the above addition should look like this:

sum  = price;
  • Related