Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android dialog with custom layout: returning data

I have problem with getting data, that user inputs in dialog (with custom layout). Look at the code:

unit.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</EditText>
</RelativeLayout>

code:

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.unit, null)); 
    AlertDialog dialog = builder.create();
    dialog.show();

Dialog opens with layout I have created, but that

    builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
                        EditText text = (EditText)findViewById(R.id.editText1);
                        Toast.makeText(getApplicationContext(), text.getText(), Toast.LENGTH_SHORT).show();
            dialog.dismiss();
          }

        });

produces runtime error: java.lang.NullPointerException. Where is the problem?

like image 466
Andy Avatar asked Dec 31 '12 14:12

Andy


1 Answers

use this..

 builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
                    EditText text = (EditText) dialog.findViewById(R.id.editText1);
                    Toast.makeText(getApplicationContext(), text.getText(), Toast.LENGTH_SHORT).show();
        dialog.dismiss();
      }

    });
like image 154
Ketan Ahir Avatar answered Sep 27 '22 18:09

Ketan Ahir