如何从 Firebase 中的节点获取所有值的总和?错误

How to get a sum of all values from a node in Firebase? Error

请告诉我:我的错误是什么?我正在尝试应用您的示例,但无法获得求和结果。我想将所有价格相加并显示在 TextView 中。我将不胜感激,我是新手。 enter image description here

主要活动 包裹 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) {

    }
}

用户Class 包裹 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>

要获取User节点中每个子项下存在的所有价格字段的总和,请使用以下代码行:

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!
        }
    }
});

logcat 中的结果将是:

sum: 200

另请注意将价格存储为数字而不是而不是字符串,在这种情况下,上述添加应如下所示:

sum += price;