Search code examples
javaandroidandroid-studiosharedpreferences

How would I save the rating with a Shared Preference?


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();

       });

Solution

  • To save the rating you need to save it in your SharedPreferences. In the code below I show you how to achieve that:

    RatingBar ratingBar = findViewById(R.id.ratingbar);
            if(getRating(getApplicationContext()) != 0){
                ratingBar.setRating(getRating(getApplicationContext()));
            }
            ratingBar.setOnRatingBarChangeListener((ratingBar1, rating, fromUser) -> {
                    setRatingBar(getApplicationContext(),rating);
    
            });
    

    And here the mentioned SharedPreferences functions:

    public static SharedPreferences prefs(Context context){
            return PreferenceManager.getDefaultSharedPreferences(context);
        }
        public static void setRatingBar(Context context, float Float) {
            prefs(context).edit().putFloat("RatingBar", Float).apply();
        }
        public static float getRating(Context context) {
            return prefs(context).getFloat("RatingBar", 0);
        }