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

时间:2019-12-02 10:11:10

标签: android sharedpreferences ratingbar

我的“评价应用程序”在导航抽屉中。我具有共享的首选项,用于保存评价栏的值,但是当我再次打开时,它在评价栏中显示为空白。我在哪里弄错了? 以下是我的代码:

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

请在builder.setTitle之前编写以下代码,因为您仅在用户按下“确定”按钮后才进行初始化。

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

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