简体   繁体   中英

NullPointerException on a setText Method

I'll first give you the Java- and XML- Code and explain my problem below.

EditText et1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EditText et1 = (EditText) findViewById(R.id.et1);
}

//Called when Button clicked
public void calculate(View view) {
    et1.setText("test"); //ERROR IN THIS LINE

}

(relevant) XML-Code

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/et2"
    android:layout_below="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:inputType="numberDecimal"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btnText"
    android:id="@+id/btnCalc"
    android:layout_below="@+id/et2"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="49dp"
    android:onClick="calculate"/>

As soon as I click on the button, my app closes. In Android Studio I can see that there's a NullPointerExeption. When i write "EditText et1 = (EditText) findViewById(R.id.et1);" in the "calculate"-method everything works fine. So my questions are:

  1. Why?

  2. How to make it so that i can use the functions of the EditText et1 in every method (in this class)?

I know by reading other posts that findViewById(id) apperently gives back "null" but I used the right Id.

You are defining edit text two times, do this instead:

EditText et1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et1 = (EditText) findViewById(R.id.et1);
    }

    //Called when Button clicked
    public void calculate(View view) {
        et1.setText("test"); //ERROR IN THIS LINE

    }

You dont have R.id.et1 your id in edit text is et2

EditText et1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et1 = (EditText) findViewById(R.id.et2); // change id 
}

//Called when Button clicked
public void calculate(View view) {
    et1.setText("test"); //ERROR IN THIS LINE

}

As Aakash and Dici wrote, you're re-defining EditText et1 inside of your onCreate() method, instead of setting the attribute. Also, you're trying to set et1 to the view with the id R.id.et1 , the exception shall be triggered again as the ID you want to set it to is R.id.et2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM