I am making an android application where i got a set of strings that i load from SharedPreferences so that i can save the strings. The strings contain only numbers, but it is not an int value, its a string value. And i wounder how i can minus the numbers that's in there, becuase usually, i would have been using something like an int value = value - value; But that doesn't seem to work since it's a string and not an int value. How can i do this even though it's a string? I know i could use int values instead, but as i didn't think of this before now, when i'm almost done, it would be alot of work changing all of the code that's related to this. Please help me and thanks so much in advance!
Asked
Active
Viewed 172 times
4 Answers
3
You will have to convert your strings to ints first, then operate on them, then save the string back:
String value = preferences.getString("key:");
int intValue = Integer.valueOf(value);
intValue = intValue - 1;
preferences.edit().putString("key", Integer.toString(intValue)).commit();

K-ballo
- 80,396
- 20
- 159
- 169
-
On the last line I think you meant to put `Integer.toString(intValue)` not `value`. – Squonk Jun 09 '12 at 20:42
-
Thanks, i'll try that now, on the last line, didn't you mean to put edit().putInt instead of edit().put??? – user1446632 Jun 10 '12 at 16:39
-
@user1446632: Sure, `putInt`, it always confuses me how some functions are just `put` and overloaded while others are named.. the inconsistencies within the _Android framework_. – K-ballo Jun 10 '12 at 16:41
-
I know, i actually meant putString, however, i tried the code and got it into my code and it is working awesome! Thanks SO much! – user1446632 Jun 10 '12 at 17:03
0
Learning basic programming the the concept of casting will help you tremendously. One datatype can be converted to another using the base classes, which often times deal with String. For instance look at the Documentation of Integer.

JoxTraex
- 13,423
- 6
- 32
- 45
0
Well as you have said that it is a lot of work to change the code and save it as int, I would suggest converting the string into an integer, refer to this link for more information, someone has asked about converting strings to integers, and as Android is Java-based, this can apply to your project:
Converting a string to an integer on Android
Hope this helps.