1

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.

Aiden Nox
  • 23
  • 5

2 Answers2

2

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)
laalto
  • 150,114
  • 66
  • 286
  • 303
1

Change

EditText txt = (EditText) view.findViewById(R.id.editText);

to

EditText txt = (EditText)findViewById(R.id.editText);

Your are looking for your EditText control in the View which was clicked - and that's obviously the Button. You have to search through the Activity's layout file.