I am trying to implement a rating bar within an AlertDialog. I have the rating bar working but I can’t seem to make the SharedPreference work to remember what star rating was inputted beforehand. Where/How should I put the SharedPreference to make it work?
Here is the code for the rating AlertDialog:
private float rateValue;
rating.setOnClickListener(clk ->{
AlertDialog.Builder mBuild = new AlertDialog.Builder(SoccerItemDetailHostActivity.this);
mBuild.setTitle("Please rate the app");
View mView = getLayoutInflater().inflate(R.layout.soccerratingbar,null);
final RatingBar ratebar = (RatingBar)mView.findViewById(R.id.ratingBar);
ratebar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rateValue = rating;
Toast.makeText(SoccerItemDetailHostActivity.this, ""+rating, Toast.LENGTH_SHORT).show();
}
});
Button btnSubmit=(Button)mView.findViewById(R.id.btnSubRating);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(SoccerItemDetailHostActivity.this, ""+rateValue, Toast.LENGTH_SHORT).show();
}
});
mBuild.setView(mView);
AlertDialog dialog=mBuild.create();
dialog.show();
});
2
Answers
Well, what have you tried? Your code doesn’t show any attempt at using SharedPreferences so it’s impossible to say what you’re doing wrong.
You could probably add an onDismissListener to the dialog that saves the current rating.
To save the rating you need to save it in your
SharedPreferences
. In the code below I show you how to achieve that:And here the mentioned
SharedPreferences
functions: