Issue
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" />
Solution
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
Answered By - Antony Aiwin K X
Answer Checked By - Katrina (JavaFixing Volunteer)