-1

Today I am tried to make a calculator, but my clear button is throwing error . java.lang.IndexOutOfBoundsException: setSpan (5 ... 5) ends beyond length 4

MainActivity.java looks like this,

       binding.clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateText("");
            }
        });

And My activity_main.xml file looks like this,

<com.google.android.material.button.MaterialButton
                android:id="@+id/clearBtn"
                android:layout_width="0dp"
                android:layout_height="70dp"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:backgroundTint="#FF9800"
                android:text="@string/clear"
                android:textSize="24sp"
                app:cornerRadius="19dp" />
Anindra
  • 11
  • 4
  • Does this answer your question? [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – a_local_nobody Nov 15 '21 at 16:41

1 Answers1

0

I think you passed an empty string with zero characters in this function updateText(""). There is no text inside the "" tag. So it will crash because you are trying to setSelection in the editText with character less than (cursorPosi + 1) in this line.

binding.display.setSelection(cursorPosi + 1);

To fix this error you can try calling the function with white space:

updateText(" ");

But I wonder that you will need to clear all character or detele the character at cursor of the EditText when you click on clear button