I am creating a feedback app where the user rates a service from 1-5 and I display the average of all the user's ratings (till date) on the next page. The average rating is coming out to be fine but I am not able to fetch the total number of users from snapshot that have rated on the app till now.
Here is the code -
public class Score extends AppCompatActivity {
TextView avgScore;
TextView totalUsers;
double userCount;
DatabaseReference dbRef;
@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("Users");
scoreRealTime();
}
public void scoreRealTime() {
dbRef.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(String.valueOf(helper.rating));
// double values = Double.parseDouble(ds.child("rating").getValue().toString());
total = total + values;
userCount = snapshot.getChildrenCount();
}
double average = (double) total / snapshot.getChildrenCount();
avgScore.setText(String.format("%.2f", average));
//System.out.println(userCount);
totalUsers.setText((int) userCount); //error occurs here
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
This is the error log -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.feedback, PID: 26338
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference
at com.example.feedback.Score$1.onDataChange(Score.java:60)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
EDIT: Also, it would be really great if you could explain why the NullPointerException is occurring here or occurs in general. Thanks.