Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Preferences API working on both Android and PC

Tags:

java

android

I'd like to save user preferences from a sketch running either on a PC or an Android phone, using the same code in as standard "Java-way" as possible.

Ideal candidate for my purposes seems to be the java.util.prefs.Preferences class. So, I wrote a little test script to see if it's working in processing:

String prId = "counter";
Preferences prefs = Preferences.userNodeForPackage(this.getClass());
int counter = prefs.getInt(prId, 0);

println(counter);
prefs.putInt(prId, 1+counter);

This program outputs an increasing number each time it is executed - on a PC. On Android, the default value (0) is always shown. Are there any additional steps required to get this working on Android? Permissions to be requested? Are there any alternatives for saving name - value pairs on both platforms?

Obs.: "WRITE_EXTERNAL_STORAGE" permission is already enabled

like image 367
user1352652 Avatar asked Nov 03 '22 03:11

user1352652


1 Answers

This is a known Android bug unfortunately: https://code.google.com/p/android/issues/detail?id=22232

Basically the app does not have write permissions for the generated path, which should be a system-specific location where the user has write permissions instead.

Simplest (cross platform) workaround could be to use java.util.Properties, where you have control over the storage location.

Another workaround (if you are tied to the Preferences API for some reason) might be to provide your own implementation of AbstractPreferences (perhaps backed by Android SharedPreferences?), see this SO post: Is there a way to use java.util.Preferences under Windows without it using the Registry as the backend?

P.S.: Another workaround option might be to explicitly export / import the data using Preferences.exportSubtree(OutputStream os) and Preferences.importPreferences(InputStream is)

like image 194
Stefan Haustein Avatar answered Nov 15 '22 00:11

Stefan Haustein