Search code examples
javaandroidonclicksettext

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.


Solution

  • 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
    
        }