aggregate1166877
aggregate1166877

Reputation: 3150

Null pointer exception occurs when calling getText from EditText in OnClickListener

I have a custom dialog box. When i click "OK", I would like it to get the text from its EditText field. However, it throws a null pointer exception.

Code:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_delivered, (ViewGroup)findViewById(R.id.llDeliveredDialog));

builder.setMessage("Dialog message");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    final EditText text = (EditText)findViewById(R.id.etGivenTo);
    String value = text.getText().toString();
    }
});

builder.setCancelable(false);
builder.setView(layout);
builder.show();

XML Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llDeliveredDialog"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/etGivenTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

</LinearLayout>

Any help would be much appreciated.

Upvotes: 0

Views: 2901

Answers (2)

Aerrow
Aerrow

Reputation: 12134

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    final EditText text = (EditText)layout.findViewById(R.id.etGivenTo); 
    String value = text.getText().toString();
    }
});

Upvotes: 1

Samir Mangroliya
Samir Mangroliya

Reputation: 40416

 final EditText text = (EditText)layout.findViewById(R.id.etGivenTo);
                                 ^^^^^^

Upvotes: 7

Related Questions