I’m trying to write a small bit of binary data as a string to SharedPreferences. I may be grossly misunderstanding encoding here, but this is what I’m trying to do:
String str = new String("hi there!".getBytes(), "ISO-8859-1");
SharedPreferences p = context.getSharedPreferences("foo", MODE_PRIVATE);
Editor e = p.edit();
e.putString("string", str);
e.putBoolean("worked", true);
e.commit();
... later on after an app restart...
// the shared prefs file will be empty upon the next app start:
SharedPreferences p = context.getSharedPreferences("foo", MODE_PRIVATE);
Log.d(TAG, "String value present?: " + p.getString("string", null));
Log.d(TAG, "Boolean flag present?: " + p.getBoolean("worked", false));
The commit() call returns true, everything seems ok. The next time I start this demo app, I read the contents of this shared prefs instance, and it’s completely empty. If I don’t use the “ISO-8859-1” encoding, then everything works as expected, the shared prefs file has the key values in it.
Can shared prefs not work with a string using that encoding?
Thanks
SharedPreferences is probably treating the strings as UTF-8 encoded, and you are giving it strings that are ISO-8859-1 encoded. These two encodings are not compatible so that’s probably why you’re seeing this issue.
Do you have to use ISO-8859-1 encoding? Can you set the encoding to UTF-8 or leave it blank entirely(I believe Java will store it as UTF-16 encoded bytes by default)? This is generally a safer choice to use when you can.