简体   繁体   English

SharedPreferences无法按预期工作,无法读取或写入首选项

[英]SharedPreferences not working as expected, cannot read nor write preferences

private void init() {

    SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);

    // SET VALUE RECORD

    record = prefs.getInt("record", 0);

    prefs.edit().commit();
}

private void setRecord(int i ) {

    SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);

    if(i > prefs.getInt("record", 0))
        prefs.edit().putInt("record", i);

    prefs.edit().commit();
}

private int getRecord() {

    int rec;

    SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);

    rec = prefs.getInt("record", 0);

    prefs.edit().commit();

    Toast toast = Toast.makeText(this, rec+"", Toast.LENGTH_SHORT);
    toast.show();

    return rec;
}

this code should set an int and retrieve it, but it doesn't seem to ever set it... can you see why is that? 这段代码应该设置一个int并检索它,但它似乎没有设置它......你能看出为什么会这样吗?

try 尝试

Editor editor = prefs.edit();
editor.putInt("record",i);
editor.commit();

Think it is best to call the interface SharedPreferences.Editor to edit preferences instead of using prefs.edit().putInt("record", i); 认为最好调用接口SharedPreferences.Editor来编辑首选项,而不是使用prefs.edit().putInt("record", i); . The docs say... 文件说......

Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. 对首选项的修改必须通过SharedPreferences.Editor对象,以确保首选项值保持一致状态,并在提交存储时进行控制。

If you change your setMethod to the following it should work... 如果你将setMethod改为以下它应该工作...

private void setRecord(int i ) {

    SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    if(i > prefs.getInt("record", 0))
        editor.putInt("record", i);

    editor.commit();
}

And I guess you are calling the above method setRecord somewhere in your code as I can't see it being called anywhere in the code snippet you pasted. 我猜你在代码中的某个地方调用了上面的方法setRecord ,因为我看不到它在你粘贴的代码片段中的任何地方被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM