Search code examples
javaandroidnullpointerexceptionfindviewbyid

Android findViewById null pointer


From activity_settings.xml

<EditText android:id="@+id/editText" android:text="text" />
<Button android:id="@+id/button" android:text="button"/>

From MyActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    this.findViewById(R.id.button).setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText txt = (EditText) view.findViewById(R.id.editText);
                Toast.makeText(view.getContext(),txt.getText(), Toast.LENGTH_SHORT).show();
           }
        });
...

If I click the button I get

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

Just for test I tried and succeeded

@Override
public void onClick(View view) {
    EditText txt = (EditText) view.findViewById(R.id.editText);
    Toast.makeText(view.getContext(),txt.getText(),Toast.LENGTH_SHORT).show();
    }
}

I don't get why button is ok but editText is null.


Solution

  • You're calling findViewById() on the view that was clicked. Your button does not have the edittext as its child. You should query the activity view hierarchy instead: replace

    view.findViewById(R.id.editText)
    

    with

    findViewById(R.id.editText)