0

I am trying to limit the edit text value to be less than or equal to 130. In the onCreate method, I did the following:

final EditText expectedYears = (EditText)findViewById(R.id.lifespan);
expectedYears.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){
          if(Integer.parseInt(s.toString())>130){
                expectedYears.setText(String.valueOf(130));
          }

      }
});

I am not really sure why the app crashes after this. By testing, I figured out that the expectedYears.setText line is causing this. I feel like once I set the text, the onTextChanged function gets called again. How can I fix this?

Stack Trace

 at android.widget.EditText.setText(EditText.java:113)
 at android.widget.TextView.setText(TextView.java:5209
 at net.msolonko.motivation_app.MainActivity$1.onTextChanged(MainActivity.java:49) 
 at android.widget.TextView.sendOnTextChanged(TextView.java:9364)
 at android.widget.TextView.setText(TextView.java:5397)
 at android.widget.TextView.setText(TextView.java:5250)
shurup
  • 751
  • 10
  • 33

2 Answers2

1

According to this question, you should not change the text of the EditText being watched in onTextChanged(). My guess is that it results in an infinite recursion loop.

Instead, try putting your logic setting the text in afterTextChanged().

Adam Adli
  • 96
  • 4
0

setText() method requires string type argument, make sure that you are passing string type argument,can use type casting

mudassir ahmed
  • 191
  • 1
  • 1
  • 13