Search code examples
androidnullpointerexceptionandroid-textwatcher

Accessing TextWatcher in another class - nullpointer exception


I have one activity and one of its function logic is calculated in another class, here i calculate when something is entered in the edit text field, i use a text watcher.

MainActivity code:

public class UnitConverter extends AppCompatActivity {
    public EditText input;
    .
    ......
    input = (EditText) findViewById(R.id.etInput);
    .........
    case Sample :
         new AnotherClass();
}

am using textwatcher on this input field,

AnotherClass code:

public class AnotherClass {
UnitConverter ac = new UnitConverter();
public AnotherClass() {
    ac.input.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) {
     }
  }
}

am getting a null pointer error,

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.addTextChangedListener(android.text.TextWatcher)' on a null object reference                                                                       

Solution

  • You need to pass your activity reference to another class to like below:

    MainActivity code:

    public class UnitConverter extends AppCompatActivity {
        public EditText input;
        .
        ......
        input = (EditText) findViewById(R.id.etInput);
        .........
        case Sample :
            new AnotherClass(UnitConverter.this);
    }
    

    AnotherClass code:

    public class AnotherClass {
        public AnotherClass(UniteConverter ac) {
        ac.input.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) {
          }
      }
    }