Converting a string to an integer on Android
To convert a string to an integer in Android, you can use the Integer.parseInt
method.
Here is an example of how you can do this:
String string = "123";
int number = Integer.parseInt(string);
This will convert the string "123" to the integer 123.
Note that the parseInt
method can throw a NumberFormatException
if the string is not a valid integer. You should handle this exception in your code.
try {
int number = Integer.parseInt(string);
} catch (NumberFormatException e) {
// handle the exception
}
Alternatively, you can use the Integer.valueOf
method to convert a string to an integer.
Here is an example of how you can do this:
int number = Integer.valueOf(string);
This will also convert the string "123" to the integer 123.
Note that the valueOf
method returns an Integer
object, rather than an int
primitive. If you need an int
primitive, you can use the intValue
method of the Integer
object.
int number = Integer.valueOf(string).intValue();