Home » Android » android – Set value in RatingBar

android – Set value in RatingBar

Posted by: admin May 14, 2020 Leave a comment

Questions:

I can’t set rating for the RatingBar. My code below. How can I set a default rating for dynamically added RatingBar?
Here is my code.

public class DialogRate extends Activity implements OnRatingBarChangeListener {
...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog_layout);
    LinearLayout ll_dialog = (LinearLayout) findViewById(R.id.linearLayout_dialog);     
    final RatingBar rate_bar = new RatingBar(context);
    rate_bar.setOnRatingBarChangeListener(this);
    rate_bar.setStepSize((float) 0.5);
    rate_bar.setMax(5);
    rate_bar.setId(1);   
    rate_bar.setRating(2.0f); // Error occur on this line!
    ll_dialog.addView(rate_bar);
}
...
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
     // TODO Auto-generated method stub
     TextView rate_val = (TextView) findViewById(0);
     rate_val.setText(Float.toString(ratingBar.getRating()));
}

Error Stack:

Thread [<1> main] (Suspended)   
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1645    
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1663 
ActivityThread.access$1500(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 117   
ActivityThread$H.handleMessage(Message) line: 931   
ActivityThread$H(Handler).dispatchMessage(Message) line: 99 
Looper.loop() line: 123 
ActivityThread.main(String[]) line: 3683    
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
Method.invoke(Object, Object...) line: 507  
ZygoteInit$MethodAndArgsCaller.run() line: 839  
ZygoteInit.main(String[]) line: 597 
NativeStart.main(String[]) line: not available [native method]  

Close

Sorry guys this error is simple. The TextView in onRatingChanged dynamically created after setRating.

How to&Answers:

You can use this code:

rate_bar.setRating(Float.parseFloat("2.0"));

or use this:

rate_bar.setRating(0.0f);

Answer:

I know this is late but for Kotlin this how you can achieve the same

`val rate=2
 rate_bar.rating = rate.toFloat()`