0

I am trying to save user preferences in Android with the following code:

import java.util.prefs.Preferences;

class MyClass {
    void save() throws Exception {
        _prefs.put("NAME","VALUE");
        _prefs.flush(); // Throws exception
    }
    private final Preferences _prefs = Preferences.userNodeForPackage(MyClass.class);
}

... but the "flush" call generates the following exception:

W/java.util.prefs: Could not lock User prefs.  Unix error code 2.
W/System.err: java.util.prefs.BackingStoreException: Couldn't get file lock.

I guessed it was a problem with permissions. So I added the following to AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_USER_DICTIONARY" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />

But I still get the exception.

How can I save user preferences in Android with the java.util.prefs.Preferences class?

Adam Gawne-Cain
  • 1,347
  • 14
  • 14

1 Answers1

0

read some doc, especially WARNING section

On Android, the Preference nodes corresponding to the "system" and "user" preferences are stored in sections of the file system that are inaccessible to apps. Further, allowing apps to set "system wide" preferences is contrary to android's security model.

instead of Preferences use SharedPreferences, some doc about in HERE

snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • I want to use java.util.prefs so I can share source code with a JRE desktop app. I did read the WARNING. I am using the recommended idiom to create the Preferences object. If it is impossible to get java.util.Prefs to work in Android then the document should say so (ideally at the top of the JavaDoc page). If it is possible then how can I do it? – Adam Gawne-Cain Jul 16 '21 at 07:01
  • well, some guy in [HERE](https://stackoverflow.com/questions/15279083/getting-preferences-api-working-on-both-android-and-pc) is pointing on [some old bug](https://issuetracker.google.com/issues/36935918) in Android. looks like you should use two different storing resolutions, depending on platform – snachmsm Jul 16 '21 at 07:09
  • Thanks snachmsm for your answer and comments. I hadn't seen the other guys essentially same question from 8 years ago. I suppose I will have to write code to save preferences in platform-dependent ways as you say. – Adam Gawne-Cain Jul 16 '21 at 08:03