Search code examples
androidandroid-edittextonclicklistener

Checking if EditText is empty via listener


I know there are several answers for this, but none seem to address my problem:

I have the following code:

   myEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

     }

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

            Log.i("Ram = ", myEditTExt.getText().toString());
            Log.i("Ram = ", s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {

            Log.i("Ram = ", myEditTExt.getText().toString());
            Log.i("Ram = ", s.toString());

        }
    });

Neither onTextChanged or afterTextChanged shows is called when the Text is made completely empty. Example Run - this is the same case whether I called the method onTextChanged or afterTextChanged.

The TextBox starts with the value of 25.0 and I click on it and delete it one character at a time and this is the output on the log

Note that I only put 1 statement - I've written all four statements for clarity on what I've tried, but any of the 4 only give me the below output:

04-11 17:24:37.661 11221-11221/zooter.com.cal I/Ram =: 25.
04-11 17:24:39.493 11221-11221/zooter.com.cal I/Ram =: 25
04-11 17:24:41.198 11221-11221/zooter.com.cal I/Ram =: 2

What am I doing wrong??


Solution

  •         @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                if (s.toString().length() == 0) {
                    Log.i("Ram = ", "Empty");
                    Log.i("Ram = ", "");
                }
    
                Log.i("Ram = ", myEditText.getText().toString());
                Log.i("Ram = ", s.toString());
            }
    

    android.util.Log doesn't work if the log message is empty. (see second log call inside if condition doesn't work). However I think you're not using the tag correctly. I suggest doing the following:

    private static final String TAG = "RAM";
    ...
        myEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                Log.i(TAG, "Ram: " + s.toString());
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
                Log.i(TAG, "Ram: " + s.toString());
    
            }
        });
    

    Or set TAG to the Activity name (actually TAG is only useful for filtering logcat)