-1

1 つのアクティビティがあり、その関数ロジックの 1 つが別のクラスで計算されます。ここでは、編集テキスト フィールドに何かが入力されたときに計算し、テキスト ウォッチャーを使用します。

MainActivity コード:

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

inputこのフィールドでtextwatcher を使用しています。

別のクラス コード:

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) {
     }
  }
}

ヌル ポインター エラーが発生しています。

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

1 に答える 1

1

以下のように、アクティビティ参照を別のクラスに渡す必要があります。

MainActivity コード:

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

別のクラス コード:

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) {
      }
  }
}
于 2016-06-01T10:33:00.900 に答える