【发布时间】:2020-06-26 02:26:10
【问题描述】:
我有int 值,当我们单击警报对话框的正或负按钮时,我希望它增加 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);
}
【问题讨论】:
-
@PhanVanLinh 我这样做了,但它没有存储计数器值
-
你应该用
counter++替换这个counter = counter++;。它会工作 -
@PhanVanLinh 我也这样做了,还是不行。
-
我会做同样的测试然后告诉你结果
-
请告诉我们您得到的结果。澄清你所说的不工作是什么意思。
标签: android android-studio sharedpreferences