Hafijur Rahman
Hafijur Rahman

Reputation: 53

java.lang.IndexOutOfBoundsException: setSpan (2 ... 2) ends beyond length 1

I got this exception, i am new for android so please help me.

E/UncaughtException: java.lang.IndexOutOfBoundsException: setSpan (2 ... 2) ends beyond length 1

    holder.oldLaundriesQuantityEditText.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) {

            if(s.toString().length()>0){
                int editedQuantity = Integer.parseInt(s.toString());

                if(editedQuantity==0){

                    finalHolder.oldLaundriesQuantityEditText.setText("1");

                }
                if(editedQuantity>oldLaundriesModelArrayList.get(position).getRemain_quantity()){

                    finalHolder.oldLaundriesQuantityEditText.setText(String.valueOf(
                            oldLaundriesModelArrayList.get(position).getRemain_quantity()
                    ));

                }

                finalHolder.oldLaundriesQuantityEditText.setSelection(count);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

Upvotes: 4

Views: 12622

Answers (2)

Dinash
Dinash

Reputation: 3047

This issue happens when you have already entered the text of length 2 say "10" but the remaining quantity returns a single digit one say "9", in that case the count value will be 2. And on setting selection you are using count value and there is a string of length 1 only but setting to 2.

Instead of

finalHolder.oldLaundriesQuantityEditText.setSelection(count);

use

finalHolder.oldLaundriesQuantityEditText.setSelection(finalHolder.oldLaundriesQuantityEditText.getText().toString().trim().length());

For a better and cleaner one, store the value of

String.valueOf(oldLaundriesModelArrayList.get(position).getRemain_quantity());

to a string before setting to the edittext and then use the same string object to get the length of the string.

Upvotes: 6

Rasoul Miri
Rasoul Miri

Reputation: 12222

check size this oldLaundriesModelArrayList

if(oldLaundriesModelArrayList.size() > 0 && position <= oldLaundriesModelArrayList.size() ){
    finalHolder.oldLaundriesQuantityEditText.setText(String.valueOf(oldLaundriesModelArrayList.get(position).getRemain_quantity())); 
}

Upvotes: 1

Related Questions