FindViewById from AlertDialog (with custom layout) - NullPointerException

I am trying to extract text from EditTexts in an AlertDialog that is being created, as you can see below. The problem is that I cannot get text views. All I get is a null value. Any ideas?

    final EditText editFirstname = (EditText) findViewById(R.id.editFirstname);
    final EditText editLastname = (EditText) findViewById(R.id.editLastname);

    bttAddPlayer.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);

            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            builder.setView(layoutInflater.inflate(R.layout.dialog_add_player, null))
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            databaseHelper.addPlayer(editFirstname.getText().toString(),editLastname.getText().toString());
                            playerAdapter.notifyDataSetChanged();
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
    });
}

}

+3
source share
1 answer

You need to search inside the View that you are inflating for your Warning dialog box, for example, that the bloated view looks like this:

    View view = inflater.inflate(R.layout.dialog_add_player, container);

then you will need to do

EditText editFirstName = (EditText) view.findViewById(R.id.editFirstName);
EditText editLastName  = (EditText) view.findViewById(R.id.editLastName);

, -, , , EditText, , EditText.

+2

All Articles