NullPointerException when use findViewById() in AlertDialog.Builder

无人久伴 提交于 2019-12-01 11:24:14
Khawar Raza

Change

DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker);

this line to

DatePicker datePicker = (DatePicker)adb.findViewById(R.id.datePicker);

...............

try this one:

final AlertDialog.Builder adb = new AlertDialog.Builder(this);
final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.main1, null);
adb.setView(view);
final Dialog dialog;
adb.setPositiveButton("Add",new android.content.DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int arg1) {

        DatePicker datePicker = (DatePicker)view.findViewById(R.id.datePicker1);

        java.util.Date date = null;
        Calendar cal = GregorianCalendar.getInstance();
        cal.set(datePicker.getYear(),datePicker.getMonth(), datePicker.getDayOfMonth());
        date = cal.getTime();
    }                  
});   
dialog = adb.create();
dialog.show();

Search for the DatePicker using the dialog parameter:

DatePicker datePicker = (DatePicker) ((Dialog) dialog).findViewById(R.id.datePicker);

I think this could be the problem,

final AlertDialog.Builder adb = new AlertDialog.Builder(getApplicationContext());
adb.setView(LayoutInflater.from(getApplicationContext()).inflate(R.layout.custom,null));

Use the below way to inflate the view and use the view object for getting the id.

 LayoutInflater factory = LayoutInflater.from(this);
    final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);

DatePicker datePicker = (DatePicker)textEntryView.findViewById(R.id.datePicker1);

Example:

protected Dialog onCreateDialog() {
    LayoutInflater factory = LayoutInflater.from(this);
    final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
    return new AlertDialog.Builder(TicTacToe.this)
        //.setIconAttribute(android.R.attr.alertDialogIcon)
        .setTitle(getTitleText())
        .setView(textEntryView)
        .setPositiveButton("JOIN GAME", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                try
                {
                    EditText et = (EditText)findViewById(R.id.username_edit);
                        playerName = et.getText().toString();
                }
                catch (Exception e)
                {
                }
            }
        })
        .create();
return null;

}

In my case: First I must call the

dialog.show(),

and only after it I was able to use

dialog.findviewById(R.id.myID).

If I missed to call the show(), than I got a null back with findViewByID.

A project clean and rebuild fixed this error for me (on Xamarin).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!