I'm updating my Android app. The app retrieves data from my server and among that data is a user id. The user id is a number (Integer) but it arrives from the server as a string eg "1234". In the old version I then saved this user id as a string in my shared prefernces but now that I'm looking back at it I don't like this and want to save it as an Integer as it should be.
So far pretty simple. I just use putInt / getInt rather than putString / getString. The problem is that all the people currently using the app will have the value saved in their shared preferences as a string and then when they update the app the new version of the app will start to try to use getInt to get the value which the old version saved as a string.
What's the best way to avoid any errors because of this and ensure a smoothe transition between the two app versions?
Thanks.
There is a limit to what we can store in SharedPreferences out of the box. In other words, we can store the following data types boolean, int, long, float, string and stringSet.
You can create a new shared preference file or access an existing one by calling one of these methods: getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.
Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory.
Yes, it is deprecated. Use the AndroidX Preference Library for consistent behavior across all devices. For more information on using the AndroidX Preference Library see Settings.
Something like that in your onCreate:
try{
prefs.getInt("key", 0);
}catch (ClassCastException e){
Integer uid = Integer.parseInt(prefs.getString("key", null);
if(uid != null)
prefs.edit().putInt("key", uid).commit();
}
This is as simple as
int userid = Integer.parseInt( preferences.getString("userid", ""));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With