javaandroidandroid-textwatcheraddtextchangedlistener

My apps crash due to hit backspace in inputfield due to afterTextChanged , how can i handle backspace for this code


public void afterTextChanged(Editable editable) {

    String f = y.getText().toString();

    String[] data2 = f.split(" ");

    if (f.substring(f.length() - 1).equals(" ")) {
        StringBuilder M = new StringBuilder();
        String z = y.getText().toString();
        String[] data1 = z.split(" ");
        {
            String last = order(data1[data1.length - 1].toString());

            data1[data1.length - 1] = last.toString();

            for (int i = 0; i < data1.length; i++) {

                M.append(data1[i]);
                M.append(" ");

            }

            y.removeTextChangedListener(this);
            y.setText(M.toString());
            y.setSelection(y.getText().length());
            y.addTextChangedListener(this);

        }
    }
}

this is the code of my afterchangetext in this when the space is detected it changes the previous word to its standard form but when the user write something and trying to remove or hit backspace then apps crash due to this method please elp me how to handle backspace


Solution

  • It's crashing while edit text is empty because of using substring method on empty string.

    if (f.substring(f.length() - 1).equals(" ")) {

    Replace like this:

    if (f.length() > 0 && f.substring(f.length() - 1).equals(" ")) {

    Let me know if it's having issue.