I am trying to create custom AlertDialog with two EditText fields for input. Here is the code:
void newItemInput(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_signin, null));
builder.setTitle("");
builder.setMessage("");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
EditText item_name = (EditText)findViewById(R.id.item_name);
EditText item_price =(EditText)findViewById(R.id.item_price);
String text = item_name.getText().toString();
String text_price = item_price.getText().toString();
int price = Integer.parseInt(text_price);
// Do something with value!
products.add(new Product(text, price, R.drawable.unread, false));
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
builder.show();
}
AlertDialog shows up and I can input data. But when I press OK, while passing text and price as arguments to products.add(new Product(text, price, R.drawable.unread, false)), app crashes down.
Here is the layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="@+id/item_name"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"/>
<EditText
android:id="@+id/item_price"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"/>
</LinearLayout>
Please let me know, what am I doing wrong. When I do not use custom Dialog and use only one text field it works fine. But I need two fields, and I am assuming that this crash because of LayoutInflater.
Firstly, in the future, when you receive LogCat errors, please post them.
Best solution is to cast the dialog to an
AlertDialog, then use that.Alternatively, if the above doesn’t work, you can save the
Viewyou give to the builder, then use that instead.Like so, using a
finalmodifier to access within theOnClickListener:Then, access
v.findViewByIdwithin theOnClickListenerto find the views.