idon'tknow
idon'tknow

Reputation: 3

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.

Upvotes: 0

Views: 69

Answers (3)

Karim Kouznetsov
Karim Kouznetsov

Reputation: 525

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.

Upvotes: 0

Aakash
Aakash

Reputation: 5261

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

    }

Upvotes: 1

Melvin Mauricio
Melvin Mauricio

Reputation: 387

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

}

Upvotes: 0

Related Questions