Dan Maia Dan Maia - 7 months ago 36
Android Question

EditText Value in a dialog

I dont understand, the dialog and everything works but as soon as I get the value from the EditText and assign it to val, run the app it crashes within the onClick on success.

I get an error: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

public void createDialogBox() {

AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = this.getLayoutInflater();

// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout

.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// On success

EditText text = (EditText) findViewById(R.id.shopping_list_recycler_view);
String val = text.getText().toString();

adapter = new ShoppingListViewAdapter(test, MainShoppingListViewActivity.this);

adapter.addTest(new Data(val, "Created by: Me"));
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// On failure
Toast.makeText(MainShoppingListViewActivity.this, "Failed", Toast.LENGTH_SHORT).show();
// Desired icon for the dialog box


06-03 22:37:29.778 21364-21364/familyshopshare.com.familyshopshare E/AndroidRuntime: FATAL EXCEPTION: main
Process: familyshopshare.com.familyshopshare, PID: 21364
java.lang.ClassCastException: android.support.v7.widget.RecyclerView cannot be cast to android.widget.EditText
at familyshopshare.com.familyshopshare.MainShoppingListViewActivity$3.onClick(MainShoppingListViewActivity.java:93)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


You need to get the view of the dialog from the LayoutInflater like this:

View rootView = layoutInflater.inflate(R.layout.dialog_layout, null);

Then you can call

EditText text = (EditText) rootView.findViewById(R.id.shopping_list_recycler_view);