Saurabh
Saurabh

Reputation: 1

Calling setText("") app getting crashed or How can i set CharSequence NULL value

Calling setText("") app getting crashed or How can i set CharSequence NULL value. Whenever i have only one character in the EditText and using Key Stroke backspace my app getting crashed.

I have an EditText with below code:

        bid_four = findViewById(R.id.bid_four);
        bid_four.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "1000")});
        bid_four.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                bid_4= Integer.parseInt(String.valueOf(s));
                total_ticket = (bid_0 + bid_1 + bid_2 + bid_3 + bid_4 + bid_5 + bid_6 + bid_7 + bid_8 + bid_9);
                total_value = (total_ticket * 11);
                total_number_of_ticket.setText(Integer.toString(total_ticket));
                total_number_of_purchase_ticket.setText(Integer.toString(total_value));
                buy_button_enable();
            }
        });

Upvotes: 0

Views: 277

Answers (1)

Eugen Pechanec
Eugen Pechanec

Reputation: 38243

Whenever i have only one character in the EditText and using Key Stroke backspace my app getting crashed.

public void afterTextChanged(Editable s) {
    bid_4= Integer.parseInt(String.valueOf(s));

When there's a one character and you delete it, there aren't any characters left. You can't make integer out of an empty string.

I suggest treating empty string as zero, if that fits your case:

if (s.length() == 0) {
    bid_4 = 0;
} else {
    bid_4 = Integer.parseInt(s.toString());
}

The exception you posted in comments doesn't correspond to the issue described in your question. Anyway, don't call TextView.setText with an integer. The integer is supposed to be a resource ID, in your case you want do display a literal integer. Make it a string first:

String.valueOf(someNumber);
someNumber + "";

You did that correctly in the code sample so you must have made mistake somewhere else.

Upvotes: 1

Related Questions