But its not working. So with little googling I changed it to this and its working, but I am not able to understand why is it so? Did I mess something in above code
You didn't really mess anything up, you just forgot to call .show()
on the dialog; i.e.:
new DatePickerDialog(getContext(), dateOnDateSetListener, year, monthOfYear, dayOfMonth).show();
The reason why it works without .show()
in the second code snippet is because there the Activity
manages the dialog and will thus take care of calling that method on the dialog that gets returned in onCreateDialog(int id)
.
Generally I'd recommend the second approach because you don't really want to manage the life cycle of dialogs yourself - simply because it's quite a pain to get it right when your activities get recreated on configuration changes etc. However, for a more modern solution, using fragments, you should look into wrapping the dialog in a DialogFragment
(there's also a version in the support library that works on pre-Honeycomb devices).