Arpit Mundra
Arpit Mundra

Reputation: 41

Android: How to fetch the key value of push()

I am making a feedback app where the customer has to submit a rating (1-5) and that data pushes onto Firebase realtime database. The database in Firebase which looks like this -

{
  "Users" : {
    "-MCHoOShwgxPE3u2drjz" : {
      "Arpit Mundra" : {
        "name" : "Arpit Mundra",
        "rating" : 5
      }
    },
    "-MCHqbF4UvX02OYJNuPv" : {
      "Ankit Mundra" : {
        "name" : "Ankit Mundra",
        "rating" : 5
      }
    },
    "-MCHr-q_amx1vBJkyq2S" : {
      "Harsh Chauhan" : {
        "name" : "Harsh Chauhan",
        "rating" : 5
      }
    }
  }
}

Now I want to calculated the average of the rating of all the users which falls under user which again falls under the push() id. My question is how do I fetch the unique push() id to extract the rating value from it?

Here is the code -

package com.example.feedback;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

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

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
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;

public class Score extends AppCompatActivity {

    TextView avgScore;
    DatabaseReference dbRef;
    String mGroupID = dbRef.child("Users").push().getKey();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
        getSupportActionBar().hide(); // hide the title bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
        setContentView(R.layout.score);
        avgScore = findViewById(R.id.textView2);
        dbRef = FirebaseDatabase.getInstance().getReference().child(mGroupID);

        scoreRealTime();
    }

    public void scoreRealTime() {
        dbRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                double total = 0;
                for (DataSnapshot ds : snapshot.getChildren()){
                    double values = Double.parseDouble(ds.child("rating").getValue().toString());
                    total = total + values;
                }
                double average = (double) total / snapshot.getChildrenCount();
                avgScore.setText(String.format("%.2f", average));
            }

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

It is throwing a NullPointerException error at String mGroupID = dbRef.child("Users").push().getKey(); line.

Thanks for any help in advance.

Upvotes: 0

Views: 142

Answers (2)

Hasnain Sabir
Hasnain Sabir

Reputation: 200

you just get the user snapshot and then get the rating fro the object sir.`

 databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");

         databaseReference .addValueEventListener(new ValueEventListener() {

    @Override

    public void onDataChange(@NonNull DataSnapshot snapshot) {

        double total = 0;

        for (DataSnapshot ds : snapshot.getChildren()){

      UserHelper helper = ds.getValue(UserHelper.class);

            double values =
         Double.parseDouble(helper.rating);

            total = total + values;

        }

        double average = (double) total / snapshot.getChildrenCount();

            avgScore.setText(String.format("%.2f", average));

         }

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

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317532

Your code here is trying to use dbRef before it is assigned a value:

DatabaseReference dbRef;
String mGroupID = dbRef.child("Users").push().getKey();

dbRef is initially null. It doesn't get a value until later when onCreate is called. What you'll have to do is wait until dbRef has a value before you call methods on it. Don't assign mGroupID immediately, and instead move the assignment after dbRef has a value.

dbRef = FirebaseDatabase.getInstance().getReference().child("Users");
mGroupID = dbRef.push().getKey();

Upvotes: 0

Related Questions