Changing the overall value of Android preferences from String to Int

I am updating my Android app. The application retrieves data from my server, and among this data is the user ID. The user ID is a number (an integer), but it comes from the server as a string, for example, "1234". In the old version, I saved this user ID as a string in my general preferences, but now when I look back at it, I don’t like it and I want to save it as a whole, as it should be.

Still pretty simple. I just use putInt / getInt, not putString / getString. The problem is that all the people who are currently using the application will have the value stored in their general preferences as a string, and then when they update the application, the new version of the application will start trying to use getInt to get the value, which is the old version saved as a string.

What is the best way to avoid errors due to this and ensure the transition between the two versions of the application?

Thanks.

+7
android sharedpreferences
source share
3 answers

Something like this 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(); } 
+5
source share

It is as simple as

 int userid = Integer.parseInt( preferences.getString("userid", "")); 
+1
source share

First of all, convert your string user id to an integer, e.g.

 int uid=Integer.parseInt("1234");//here is your string user id in place of 1234. 

and then write the uid to your general preferences using putExtra (key, intValue).

what he.

0
source share

All Articles