1

Here is the code I'm trying :

public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {

            String strEnteredVal = edtMaxAge.getText().toString();

            if(!strEnteredVal.equals("")) {
                int num = Integer.parseInt(strEnteredVal);
                if (num < 125) {
                    edtMaxAge.setText(num);
                } else {
                    Toast.makeText(getContext(), "max age should be less than 125 ", Toast.LENGTH_SHORT).show();
                    edtMaxAge.setText("");
                }
            }
            } catch (NumberFormatException ex) {
                // Do something
            }
        }

When I enter a number >= 125 I need to show a popup message, like "max age should be less than 125", without accepting the characters.

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Dolly Rosy
  • 140
  • 10

3 Answers3

2

Most likely you are facing a kind of endless recursion, when you enter some text onTextChanged method is invoked and it executes this line edtMaxAge.setText(num); which triggers onTextChanged again.

Try to use InputFilter instead of TextWatcher. Here you can find an example.

Vasyl Glodan
  • 556
  • 1
  • 6
  • 22
1
public void afterTextChanged(Editable editable) {

try {

          if(!TextUtils.isEmpty(editable) {
                initial = editable.toString();
                int num = Integer.parseInt(initial);
                if (num < 125) {
                    edtMaxAge.setText(num);
                } else {
                    Toast.makeText(getContext(), "max age should be less 
                 than 125 ", Toast.LENGTH_SHORT).show();
                    edtMaxAge.setText("");
                    return;
                }
            }

} catch (NumberFormatException ex) {
                // Do something
            }
        }
0

Use InputFilter.
It gives a lot of choices to filter your input such as capital letters, numbers within certain limit etc.
Here is the exact answer what you need

Rohit Singh
  • 16,950
  • 7
  • 90
  • 88