Search code examples
androidsharedpreferencesratingbar

how to save rating bar value using shared preferences?


my "rate the app" is in navigation drawer.i have shared preferences for saving the value of rating bar but when I open again it is showing blank in rating bar.where am I getting wrong? Following is my code:

 case R.id.nav_rate:

                    try {

                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        View layout= null;
                        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        layout = inflater.inflate(R.layout.rating, null);
                       final RatingBar ratingBar = (RatingBar)layout.findViewById(R.id.ratingBar);
                        builder.setTitle("Rate Us");
                        builder.setMessage("Thank you for rating us , it will help us to provide you the best service .");
                        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Float value = ratingBar.getRating();
                                Toast.makeText(MainActivity.this,"Rating is : "+value,Toast.LENGTH_LONG).show();
                                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
                                SharedPreferences.Editor editor = pref.edit();
                                editor.putFloat("numStars", value);//put value
                                editor.commit();

                                float rating = pref.getFloat("numStars", 0f);
                                ratingBar.setRating(rating);//save
                            }
                        });
                        builder.setNegativeButton("No,Thanks", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setCancelable(false);
                        builder.setView(layout);
                        builder.show();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }}

Solution

  • Please write below code before builder.setTitle because You are only initializing after user presses OK button.

    haredPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
    
                                    float rating = pref.getFloat("numStars", 0f);
                                    ratingBar.setRating(rating);