0

I am trying to use the below code to catch when a user enters the @symbol and then higlights the proceeding text in the tag_color, no matter where it is typed within the mPostTextView. I am still relatively new to android development so im not to sure why I am getting the below error message referring to, java.lang.IndexOutOfBoundsException: charAt:.... as shown below which seems to be related to the length of the charAt(start) statement. Can anyone shed light on this?

 @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                //@Mentions for tagging user
                if (charSequence.charAt(start) == '@') {
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(mPostToText.getText().toString());
                    ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.tag_color));
                    spannableStringBuilder.setSpan(foregroundSpan, start, spannableStringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    mPostToText.setText(spannableStringBuilder);

                }

this is from the log

java.lang.IndexOutOfBoundsException: charAt: 22 >= length 22
    at android.text.SpannableStringBuilder.charAt(SpannableStringBuilder.java:119)
    at com.tradezapp.tradezapp.gui.activity.CreatePostActivity$CreatePostFragment$2$override.onTextChanged(CreatePostActivity.java:193)
    at com.tradezapp.tradezapp.gui.activity.CreatePostActivity$CreatePostFragment$2$override.access$dispatch(CreatePostActivity.java)
    at com.tradezapp.tradezapp.gui.activity.CreatePostActivity$CreatePostFragment$2.onTextChanged(CreatePostActivity.java)
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Brummerly
  • 90
  • 1
  • 11

1 Answers1

0

try this, also check for charSequence lenght,

if (charSequence!=null && String.valueOf(charSequence.charAt(count-1)).equal("@")) {
....}
kuber singh
  • 289
  • 1
  • 5
  • Sorry I should have clarified this better. I want to detect whenever @ is entered no matter where within mPostText not just at the beginning – Brummerly Oct 16 '18 at 11:14