简体   繁体   中英

Why does it go to exception when parse to integer?

I can´t figure out why this Integer.parseInt makes an exception, its a NullpointerException..

try
{
    int numberOfPictures = Integer.parseInt(editTextNumberOfGames
                        .getText().toString()); 
    Toast toast =Toast.makeText(getBaseContext(), "ratt", Toast.LENGTH_SHORT); 
                toast.show();
} catch (Exception e)
{
    Toast toast =Toast.makeText(getBaseContext(), "fel", Toast.LENGTH_SHORT); 
                toast.show();
}

Have you used a debugger to verify that editTextNumberOfGames is not null when you get to this code?

You can temporary break up the Integer.parseInt(editTextNumberOfGames.getText().toString()) statement to see exactly which part of the compound statement is causing the exception.

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

As ratchet freak pointed out in comments, i had not done this:

editTextNumberOfGames = (EditText)findViewById(R.id.editTextNrOfPictures);

Thanks for all help though.

It throws an expecption because editTextNumberOfGames is null

initialize editTextNumberOfGames correctly, or if for whatever reason you cannot garuantee, that it is initialized then

int numberOfPictures;
if (editTextNumberOfGames != null) {
   numberOfPictures = Integer.parseInt(editTextNumberOfGames.getText());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM