简体   繁体   English

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

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

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.我想将所有价格加起来并显示在 TextView 中。我将不胜感激,我是新手。 enter image description here在此处输入图像描述

MainActivity package com.example.testkorzne; 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;用户 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

<?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>

To get the sum of all price fields that exist under each child in the User node, please use the following lines of code:要获取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!
        }
    }
});

And the result in the logcat will be: logcat 中的结果将是:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM