I have int
value,我希望当我们单击警报对话框的正或负按钮时它会增加 1,并且即使用户关闭应用程序也存储 int 值。我已经完成了这些,但我不知道为什么这不起作用。
int counter;
在 oncreate 中
initA();
private void initA(){
if(getCounter() < 1)
{makeAlertDialogOther();}
}
private void makeAlertDialogOther() {
new AlertDialog.Builder(getActivity())
.setMessage(Constant.SETTINGS.getEntranceMsg())
.setCancelable(false)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
counterU();
}
})
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
counterU();
}
})
.show();
}
这是我进行共享偏好的地方:
private void counterU() {
sp = getActivity().getSharedPreferences("MyPrfs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int oldCounter = sp.getInt("counterValue", 0);
editor.putInt("counterValue", oldCounter + 1);
editor.apply();
}
private int getCounter() {
sp = getActivity().getSharedPreferences("MyPrfs", Context.MODE_PRIVATE);
return sp.getInt("counterValue", 0);
}