How to fix String Index Out of Range?

My code ran perfectly yesterday and I saved multiple backups at different stages, all of which worked yesterday. This is the specific snippet of code that worked yesterday but today is providing me with an error: Thanks in advance.

if ((!replaceThis.equals(null)) && !itsInDictionary) {
                        suggestions.setText(ReplaceAt(text, replaceThis, 
checkDictionary(replaceThis))); //this one is 183

String ReplaceAt (String input, String search, String replace){
   //Log.d("Playing", "ReplaceAt is running");
   int start = input.lastIndexOf(search);
   int len = search.length();
   int end = start+len;
   String word = input.substring(0, start)//this one is 410
           + input.substring(start, end).replace (search, replace)
           + input.substring(end);
    return word;


E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.spellingsclient, PID: 5687
    java.lang.StringIndexOutOfBoundsException: String index out of range: -1
        at java.lang.String.substring(
        at     com.example.spellingsclient.SpellingsClient.ReplaceAt(
        at     com.example.spellingsclient.SpellingsClient$2.onTextChanged(
        at android.widget.TextView.sendOnTextChanged(
        at android.widget.TextView.handleTextChanged(
        at android.widget.TextView$ChangeWatcher.onTextChanged(
        at android.text.SpannableStringBuilder.sendTextChanged(
        at android.text.SpannableStringBuilder.replace(
        at android.text.SpannableStringBuilder.replace(
        at android.text.SpannableStringBuilder.replace(
        at android.view.inputmethod.BaseInputConnection.replaceText(
        at android.view.inputmethod.BaseInputConnection.commitText(
        at android.os.Handler.dispatchMessage(
        at android.os.Looper.loop(
        at java.lang.reflect.Method.invoke(Native Method)

1 answer

  • answered 2019-06-12 17:10 contaminate

    Solved it. When I installed a new virtual device, I forgot to turn off its autocorrect. The autocorrect was what was messing up my code. Makes sense since only incorrectly spelled user input was causing the crash. Works fine now that I turned it off.

    (Not sure what's up with the downvotes though. Did I format my question incorrectly? I tried. Sorry if I did.)