title: Android: infinite loop in EditText TextWatcher
body: <p>I have two problems with this piece of code. Thanks to some nice guys here in a previous question I got it to work properly, but now I see myself in an infinite loop again and I don't get where that comes from. What I'm trying to do here is a hangman game: process a single character read in an EditText (litera) and I search for it in a word (cuvAles), then I want to replace the underscore with the respective letter.</p>
  
  <p>Here's the function that's with the problem:</p>
  
  <pre><code>litera.addTextChangedListener(new TextWatcher(){
              public void afterTextChanged(Editable s) {}
              public void beforeTextChanged(CharSequence s, int start, int count, int after){}
              public void onTextChanged(CharSequence s, int start, int before, int count){
                   String ghici = litera.getText().toString();
  
                  if(!ghici.equals("")){
                  System.out.println(ghici);
                  litera.setText("");
  
                  if(cuvAles.contains(ghici)){
                      int poz = 0;
                      while(cuvAles.indexOf(ghici, poz)!= -1){
                          poz = cuvAles.indexOf(ghici);
                          String spatii = cuvant.getText().toString();
                          String spatii2 = spatii.substring(0, poz*2-1) + ghici + spatii.substring(poz*2+1, spatii.length()-2);
                          cuvant.setText(spatii2);
                      }
                  }
                  else gresite.append(ghici+" ");
                  } 
              }   
          }); 
  </code></pre>
  
  <p>There are two problems here:</p>
  
  <p>1) <code>String spatii2 = spatii.substring(0, poz*2-1) + ghici + spatii.substring(poz*2+1, spatii.length()-1);</code> throws a StringIndexOutOfBounds exception. I think it's the spatii.length() part, but I tried with -2 and it still doesn't work. The reason the word is not matched with the underscores is that I have spaces between them to be clear.</p>
  
  <p>2) If I remove the other problem (replace the string with a constant one), I get an infinite loop (I think it's an infinite loop because the program stops responding and I see the GC in the logcat working frantically).</p>