我的“评价应用程序”位于导航抽屉中。我具有共享的偏好设置,用于保存评价栏的值,但是当我再次打开时,它在评价栏中显示为空白。我在哪里弄错了?以下是我的代码:
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变量中是否存在任何数据,如果存在任何数据,则基于该数据。
请在builder.setTitle
之前写以下代码,因为您仅在用户按下OK按钮后才进行初始化。
haredPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
float rating = pref.getFloat("numStars", 0f);
ratingBar.setRating(rating);