共享首选项以存储int值

时间:2020-06-26 02:26:10

标签: android android-studio sharedpreferences

我有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);
    }

1 个答案:

答案 0 :(得分:2)

代码无法正常工作的原因:每次关闭并再次打开屏幕时,都会开始将新的计数器值(从0开始)再次保存到SharedPreferences
解决方案:每当我们开始将计数器保存到SharedPreferences时,我们首先在SharedPreferences中获得计数器的旧值,然后增加并保存回来。

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