-1

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!

4 Answers 4

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();
Sign up to request clarification or add additional context in comments.

4 Comments

On the last line I think you meant to put Integer.toString(intValue) not value.
Thanks, i'll try that now, on the last line, didn't you mean to put edit().putInt instead of edit().put???
@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.
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!
1

Try using Integer.valueOf(string) or Integer.parseInt(string).

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.