Skip to content

Instantly share code, notes, and snippets.

Created October 13, 2017 08:58
Show Gist options
  • Save anonymous/195c491013a447d27c42adf7c281199a to your computer and use it in GitHub Desktop.
Save anonymous/195c491013a447d27c42adf7c281199a to your computer and use it in GitHub Desktop.
StackOverflow 46645568
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RatingBar
android:id="@+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="0.5"/>
</LinearLayout>
package com.example.sandbox;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.RatingBar;
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 com.example.sandbox.R;
public class FirebaseActivity extends AppCompatActivity {
private FirebaseDatabase database;
private RatingBar ratingBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = FirebaseDatabase.getInstance();
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
testRatingBar();
}
private void testRatingBar() {
final DatabaseReference ref = database.getReference("ratingbar").child("rating");
ref.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) { }
});
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
if (fromUser) ref.setValue(rating);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment