共享首选项和模拟器



我有一段简单的代码:

        SharedPreferences settings = getSharedPreferences(Constants.USER_DETAILS, 0);
        SharedPreferences.Editor editor = settings.edit();
        //editor.putLong(Constants.USER_DETAILS_SIGNEDINON, registerResponse.getSignedInOn()); // signed in on
        editor.putLong(Constants.USER_DETAILS_SIGNEDINON, 1); // signed in on
        long test = settings.getLong(Constants.USER_DETAILS_SIGNEDINON, 2);
        if (settings.edit().commit()) {
            System.out.print("ok");
        } else {
            System.out.print("not ok");
        }

正如你所看到的,我一直在玩弄以了解正在发生的事情。

所以,我已经检查了/数据/数据/...并且首选项文件确实已创建,但为空(仅地图标签)

测试长变量返回 2,即使我之前将其设置为 1 行。提交返回 true。

我错过了什么吗?

我已经设置了使用权限安卓:名称=android.permission.WRITE_EXTERNAL_STORAGE 尽管我相信只有当我真正进行外部存储时才需要这样做。

问候。大卫。

我遇到的一件事是你不能继续调用pref.edit()并期望你的更改能够持续存在。似乎每次调用 pref.edit() 都会生成一个新的编辑器(而不是单例)。

不会持久:

pref.edit().remove("key"); // new editor created
pref.edit().commit();      // new editor created

将持续:

Editor edit=pref.edit();   // new editor created
edit.remove("key");        // same editor used
edit.commit();             // same editor used

试试这段代码。

    SharedPreferences settings = getSharedPreferences(Constants.USER_DETAILS, 0);
    SharedPreferences.Editor editor = settings.edit();
    //editor.putLong(Constants.USER_DETAILS_SIGNEDINON, registerResponse.getSignedInOn()); // signed in on
    editor.putLong(Constants.USER_DETAILS_SIGNEDINON, 1); // signed in on
    if (editor.commit()) {
        System.out.print("ok");
    } else {
        System.out.print("not ok");
    }
    long test = settings.getLong(Constants.USER_DETAILS_SIGNEDINON, 2);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref",  0);        0 - for private mode
Editor editor = pref.edit();
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes

最新更新