Problem with SharedPreferences with the string "ISO-8859-1"?

I am trying to write a small bit of binary data as a string in SharedPreferences. I can make a big mistake in the encoding here, but this is what I am 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 looks fine. The next time I ran this demo application, I read the contents of this shared instance of prefs and it is completely empty. If I do not use the encoding "ISO-8859-1", then everything works as expected, the general prefs file has key values ​​in it.

Can general prefs not work with a string using this encoding?

thanks

+4
source share
2 answers

SharedPreferences probably treats the strings as UTF-8 encoded, and you pass the strings that are ISO-8859-1 encoded. These two encodings are incompatible, so you are probably seeing this problem.

Do you need to use ISO-8859-1 encoding? Can you set the encoding to UTF-8 or leave it blank completely (I assume that Java will store it as UTF-16 encoded bytes by default)? This is usually a safer choice when you can.

+1
source

In the first line, getBytes () is called without specifying a character encoding, so you go to UTF8 bytes. This works because you use the Latin characters 1, but if you use Cyrillic or Greek, it will work. What is the point of this? Strings are stored as UTF16 in memory

+1
source

Source: https://habr.com/ru/post/1436823/


All Articles