Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when use findViewById() in AlertDialog.Builder

This is my code

@Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(getApplicationContext());
adb.setView(LayoutInflater.from(getApplicationContext()).inflate(R.layout.custom, null));

adb.setPositiveButton("Add",new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {

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

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

I have the NullPointerException in this line, and I think datePicker wasn't findById, because I use AlertDialog.Builder.

cal.set(datePicker.getYear(),datePicker.getMonth(), datePicker.getDayOfMonth());

I tried use adb.findViewById(); but it'is a mistake (The method findViewById(int) is undefined for the type AlertDialog.Builder). Can you help me, please?

like image 824
pavelartlover Avatar asked Nov 28 '25 06:11

pavelartlover


2 Answers

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();
like image 101
Khawar Raza Avatar answered Nov 30 '25 20:11

Khawar Raza


Search for the DatePicker using the dialog parameter:

DatePicker datePicker = (DatePicker) ((Dialog) dialog).findViewById(R.id.datePicker);
like image 32
user Avatar answered Nov 30 '25 20:11

user