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.
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", ""));
First of all convert you string user id into integer like,
int uid=Integer.parseInt("1234");//here is your string user id in place of 1234.
and then write uid into your shared preference with putExtra(key,intValue).
that's it.
Related
In my android application I am saving the last order did in Sharedpreference. When the user check for last order I am calling Sharedprefernce and showing it. That is working perfectly. But if nothing is saved in shared preference app is crashing. So I would like to check whther sharedpreference has any values saved or not first.
String lastOrder = sharedPreferences.getString("orderNO", "");
you just need to check isEmpty of you sharedPreference value before setting it
String lastOrder = sharedPreferences.getString("orderNO", "");
if (!lastOrder.equals("")){
orderField.setText(lastOrder);
}
What to do if the TYPE of preference changed in Android Preferences? For instance if Boolean changed into ListPreference?
Really noone at Google thought about Preference Migrations?
The only sensible way for now seems to version preferences and mark for removal preferences that changed with a given version..?
Try to read key with new data type, in case of ClassCastException exception delete "old" key, and create new key with same name but new type. Something like this:
SharedPreferences prefs;
String key = "key";
prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.contains(key)) {
// key exists, so tetermine it's type
try {
prefs.edit().get<old_type_name>(key, <default_old_type_value>);
} catch (Exceprtion e) {
if (e instanceOf ClassCastException) {
prefs.edit().remove(key).apply();
}
}
}
// we are here if no key exists or key removed
prefs.edit().put<new_type_name>(key, <new_type_value>).apply();
and if needed do check if (prefs.contains(key)) ... only once on first app start.
I did something that works on raw SharedPreferences and does not need a PreferenceFragment:
introduced settings version.
preferences are stored in xml resources both with dedicated xml strings.
split code to load, migrate, set default settings on application start.
created two string arrays versions and keys - that keep track of preference changes - keys is a comma separated string - with the same index this pair keeps information on given version migration.
check the current version from stored settings and verify against versions stored in string arrays, if its current version is older (lower number) then delete keys provided in a keys string array with the same index (needs string split) and re-create them with default values.
This gives me a nice way of settings migration, based purely on strings xml resources and no code changes, also it should migrate step by step all following versions if user did not update the application frequently :-)
It is also good to mark recent migration for a user review of recent changes..
I Am writing a code using SharedPreference to store username and password of a user but each time I entered information the older one in xml file are override by newer one what I have to to to get all my data?
SharedPreferences sp1=getSharedPreferences("myshared", 0);
sp1.edit().putString("name", name.getText().toString()).commit();
sp1.edit().putString("pass", pass.getText().toString()).commit();
sp1.edit().putString("age",age.getText().toString()).commit();
sp1.edit().putString("id",id.getText().toString()).commit();
It sounds like you're overwriting your shared preferences between activities. SharedPreferences are persistent like a file on disk, so you shouldn't ever have an issue with the values not being set, hence why you must be overwriting it.
You can get your SharedPreferences by doing
SharedPreferences sp1=getSharedPreferences("myshared", 0);
String name = sp1.getString("name", "noname");
String pass = sp1.getString("pass", "nopass");
...
You can determine if the name/pass was set by checking if they equal the default value (noname and nopass in this case, though it could easily be null).
I am doing an application where I need to store some numbers and when someone call on phone I need to check if incoming number is present in my database or not.
What I did
I stored phone numbers in shared preferences. Internally android uses Map for this purpose.
Problem:
Lets say I stored 9089889899 (10 digit phone number). Now if I get an incoming call from this number it may BroadcastReceiver having 09089889899 or +91-9089889899 number for the same.
So my problem is that if I stored a number into preferences then how can I match the incoming number is present in preferences or not.
I suggest that you use something like libphonenumber to handle the phone numbers independent of the format.
There is also some functions for formatting and comparing numbers in PhoneNumberUtils.
SharedPreferences settings;
settings = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
//for get sharepref
String phone = settings.getString("9089889899", 0);
//strPhone = has your broadcast receive number
if(strPhone.contains(phone)){
}else{
}
If you are using the mobile phone as key for the sharedpreference you can:
retrive all the values of your sharedpreference: see here
iterate through the key set : see here
for every key use the contains String method: see here
Edit: why are you not use a content provider?
You can try out the following code in your BroadCast Receiver.
here "abc" with the name of your Shared Perefence. Assuming that num here is the number you got from the Broadcast Receiver:
In the code, the last 10 digits are taken out and compared, as these are what stored in SharedPreference.
SharedPreferences sp = getSharedPreferences("abc",Context.MODE_PRIVATE);
HashMap< String, String>hMap = (HashMap<String, String>) sp.getAll();
String num = "+91-9089889899";
if( hMap.containsValue(num.substring(num.length()-10))){
System.out.println("number present");
}
here is the regex that will match all the phone formats
(((([0-9]){0,1})(([0-9]){10}))|([0-9]){10}|(\+([0-9]){1,2}([0-9]{10})))
first part matches 0 - 1231231234
second part matches 1231231234
last part +91 - 1231231234
update
actually this is much better
(((([0-9]){0,1})(([0-9]){10}))|(\+([0-9]){1,2}([0-9]{10})))
I'm writing an Android application that can easily back up files and folders to the users PC. One of the things I wanted to implement was allowing the client running on the Android device to change the port I will be sending the file to.
For this, I've created an EditTextPreference to store the value.
The code I'm using to get this value back is
port = prefs.getString("serverPort", "<unset>");
However, this returns a string and I need an int, so I tried to use
sendPort = Integer.parseInt(port);
But this crashes the Android application, with (I think) a number format exception.
Is there anyway I can explicitly store the value that is entered as an Integer to make it easier?
I tried to use the method
port = prefs.getInt(...);
but that didn't work either.
Thanks for any help.
This will take whatever is entered into your edit text and put it in an int.
int yourValue = Integer.valueOf(editText.getText().toString());
Note that Integer.valueOf() will return a format exception if you put a String in it that doesn't have an integer value.
You can then use
prefsEdit.putInt("serverPort", yourValue);
prefsEdit.commit();
to save it to preferences. And this to retrieve it
int port = prefs.getInt("serverPort", -1);
Saving the port as String or int doesn't make a big difference. Either way you'll have to convert it.
Your app crashes, because it cannot convert <unset> to a number, that's where the NumberFormatException comes from.
Solution:
Catch the NumberFormatException and set sendPort to a default value.
port = prefs.getString("serverPort", "<unset>");
try {
sendPort = Integer.parseInt(port);
} catch (NumberFormatException ex) {
sendPort = 1234;
}