views:

2053

answers:

1

I'm not 100% on how to do this so i'm asking...

May seem stupid but...

How do I convert a string into an integer?

Background info: I have a textbox I have the user enter a number into...

it then:

     EditText et = (EditText) findViewById(R.id.entry1);
     String hello = et.getText().toString();

gets the string 'hello'

Now I want to convert it to a integer so I can get the number they typed in -will be used later on in code...

Is there a way to get the edittext to a integer? -That would skip the middle man... If not, string to integer will be just fine...

Thanks alot,

James

+6  A: 

See the Integer class and the static parseInt() method:

http://developer.android.com/reference/java/lang/Integer.html

Integer.parseInt(et.getText().toString());

You will need to catch NumberFormatException though in case of problems whilst parsing, so:

int myNum = 0;

try {
    myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
   System.out.println("Could not parse " + nfe);
} 
Jon
How could I assign a variable to the new integer?
James Rattray
Never mind, got it working... thanks =]
James Rattray
Sorry, did update answer with variable assignment...
Jon