如何使用共享首选项保存评分栏值?

how to save rating bar value using shared preferences?

我的 "rate the app" 在导航中 drawer.i 有保存评级栏值的共享首选项,但是当我再次打开时它在评级中显示空白 bar.where 我是不是弄错了? 以下是我的代码:

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

每当您单击并打开对话框时,它都会作为一个新实例打开,因此解决方案是在打开之前检查您的 SharedPref 变量中是否存在任何数据,如果存在任何数据,请填充您的UI 基于该数据。

请在builder.setTitle之前写下代码,因为您只是在用户按下OK按钮后才进行初始化。

haredPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode

                                float rating = pref.getFloat("numStars", 0f);
                                ratingBar.setRating(rating);