Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Android Shared Preference Value from String to Int

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.

like image 265
365SplendidSuns Avatar asked Sep 29 '15 12:09

365SplendidSuns


People also ask

What datatype is used in SharedPreferences?

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.

How can we write the shared preference to store the username and cell number of a user in Android app?

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.

What format are SharedPreferences stored in on disk?

Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory.

Is shared preferences deprecated?

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.


2 Answers

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();
}
like image 128
Prexx Avatar answered Oct 19 '22 00:10

Prexx


This is as simple as

int userid = Integer.parseInt( preferences.getString("userid", ""));
like image 34
KishuDroid Avatar answered Oct 18 '22 22:10

KishuDroid