Edoardo Tavilla
Edoardo Tavilla

Reputation: 563

Insert int type variable from EditText into SQL Database in Android

I got an EditText and I want to insert an int type variable into my database. If I insert a number, everything's ok. But if I left the EditText empty, the app crashes. This is the code that handles this and I think it's an Integer.toString() problem or something like this.

int target;

if (targetNumber.getText().toString().isEmpty()) {
        target = Integer.parseInt("");
    } else {
        target = Integer.parseInt(targetNumber.getText().toString());
    }

Upvotes: 1

Views: 62

Answers (3)

tendai
tendai

Reputation: 1250

If you'd like to make use of a ternary operator:

int target = targetNumber.getText().toString().isEmpty() ? 0 : Integer.parseInt(targetNumber.getText().toString())

Upvotes: 0

vikrant arankalle
vikrant arankalle

Reputation: 278

Replace this

 target = Integer.parseInt("");

with

target = 0;

Upvotes: 0

Artem Botnev
Artem Botnev

Reputation: 2427

You can't parse "" to int. You can store 0 for example

int target;

if (targetNumber.getText().toString().isEmpty()) {
    target = 0;
} else {
    target = Integer.parseInt(targetNumber.getText().toString());
}

Upvotes: 1

Related Questions