Search code examples
androidfirebasefirebase-realtime-databaseratingbar

How to display rating in ratingbar from Firebase?


How to display rating in the ratingbar based on Firebase? I have successfully uploaded its rating on the Firebase.

Code below shows how I uploaded the rating based on rating bar to the Firebase which works successully.

ratingRef.child("Rating").setValue(ratingstar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        Toast.makeText(UploadReviewAndRating.this, "Stars: " + (int)rating, Toast.LENGTH_SHORT).show();
    }
});

Intent intent = new Intent(UploadReviewAndRating.this, ViewProfile.class);
startActivity(intent);

Code below shows how I display the rating bar which does not work. When I run the app, the application crashes and displays error:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference.

ratingRef.child("Ratings").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int rating = dataSnapshot.getValue(int.class);
        ratingBar.setRating(rating);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Solution

  • When onRatingChanged() is called you need to save the result to the database using your ratingRef.

    ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
            if (fromUser) ratingRef.child("Rating").setValue(rating);
        }
    });
    

    And then attach a listener to the same ratingRef child to load the rating, while also checking that the returned result from the database (dataSnapshot) is not null.

    ratingRef.child("Rating").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot != null && dataSnapshot.getValue() != null) {
                float rating = Float.parseFloat(dataSnapshot.getValue().toString());
                ratingBar.setRating(rating);
            }
        }
    
        @Override
        public void onCancelled(DatabaseError databaseError) { }
    });