String Stored In Sharedpreferences Gets Modified On Each App Close?
Solution 1:
After a lot of trouble, I finally found out the root cause.
On some devices, the string values stored in SharedPreferences get its EOL characters modified. The line breaks in the string gets converted to something other than \n
which reduces the length of the string. Each line break will reduce the length of the string by 1 digit. The solution was simple:
Replace all the line breaks with \n
after each retrieval of string from the SharedPreferences.
String fixedString = problemString.replace(System.getProperty("line.separator"),"\\\n" );
also in case your string contains manually formatted string, which contains line break characters other than \n
, you should use this:
String fixedString = problemString.replace("\r\n|\n|\r", "\\\n");
UPDATE
The above solution will cause issues if you have a string which is already formatted with unix EOL characters, making it impossible to use if you have multiple strings formatted with different EOL characters. So the best approach I found is to simply replace only the carriage returns denoted by \r
StringfixedString= brokenString.replace("\r", "");
This method will remove any carriage returns in your string, so the string gets converted to (Unix LF) format from (Windows CR LF) format. The length will decrease by 1 digit on each line break. :)
Post a Comment for "String Stored In Sharedpreferences Gets Modified On Each App Close?"