Search code examples
androidevent-handlingandroid-textwatcher

Calling String methods crashes the application inside TextWatcher


I am trying to retrieve which key was pressed inside an EditText view and set it as text of a TextView in the same activity. For example, if the last key pressed was the letter 't', then I want 't' to be displayed in the TextView (and not the entire character sequence).

I tried the following:

phoneInput.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) {
        tracker.setText(s.charAt(start));
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

This resulted in a crash. I am not sure but it looks like start is index of the character that was appended when last key press occurred, so TextView should display the last character entered in EditText?

I tried this too:

phoneInput.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) {
        String sequence = s.toString();
        tracker.setText(sequence.charAt(sequence.length() - 1));
    }

    @Override
    public void afterTextChanged(Editable s) {}
});

I guess use of any String method is causing a crash, even the length(). What am I doing wrong?


Solution

  • Use below code in call back of onTextChanged()

      String text = charSequence.toString();
                if (text.length() >0) {
                    Character character = text.charAt(text.length()-1);
                    Character character1 = character;
                    tv.setText(character1.toString());
                } else {
                    // if you want to remove last character too then setText(""");
                }
    

    Hope that helps.