Android – findviewbyid (with custom layout) from alertdialog – NullPointerException

I'm trying to get text from edittexts in alertdialog, which can be seen below. The problem is that I can't retrieve textviews. All I get is a null value. Do you have 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();
        }
    });
}

}

resolvent:

You need to search the view in which you inflate the alarm dialog box. For example, your inflated view is as follows:

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

What do you need to do

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

Now it seems that you are trying to instantiate a variable for something that doesn't exist. You don't refer to the actual location of EditText. It tries to view the interior of the current view. It doesn't contain EditText

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>