0

I have this simple piece of code:

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

as you can see I have been playing around to understand what is going on.

So, I have checked the /data/data/... and the preferences file is indeed created but is empty (just the Map tag)

The test long variable returns 2, even if I set it to 1 the line before. The commit returns true.

Am I missing something?

I have set uses-permission android:name=android.permission.WRITE_EXTERNAL_STORAGE though I believe this is only needed when I truly do external storage.

Regards. David.

4

3 回答 3

3

我遇到的一件事是您不能继续调用 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
于 2014-10-26T21:49:50.157 回答
1

试试这段代码。

    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);
于 2012-10-08T10:36:11.290 回答
0
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
于 2012-10-08T10:26:52.120 回答