Search code examples
androidandroid-layoutnullpointerexceptionandroid-edittextbutterknife

EditText is null in Dialog instance


I have a dialog that pops up at first run and prompts the user to enter his/her username inside an editText view but whenever i try to access it's text by doing editText.getText(); i get a NullPointerException saying that the editText is null.What am i missing here? I tried inflating the layout and accessing the .getText() method from an Activity but nothing. Here's my code:

public class UsernameDialog extends DialogFragment {

@BindView(R.id.editText) EditText mEditText;
@BindView(R.id.username)
TextView menu_usr;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // inflate the layout using the dialog themed context
    final Context context = getActivity();
    final LayoutInflater inflater = LayoutInflater.from(context);
    final View view = inflater.inflate(R.layout.username_dialog,null,false);

    DialogInterface.OnClickListener posListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            menu_usr.setText(mEditText.getText());
            Log.d("USERNAME",mEditText.getText().toString());
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
            .setTitle("Choose your username")
            .setView(view)
            .setPositiveButton("OK",posListener);
    return builder.create();
}
}

Error log:

  Process: com.dcv.spdesigns.dokkancards, PID: 373
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
    at com.dcv.spdesigns.dokkancards.ui.UsernameDialog$1.onClick(UsernameDialog.java:48)
    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:177)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6938)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Solution

  • Add

    Butterknife.bind(this,view)