Girish Girish - 13 days ago 5
Android Question

DatePickerDialog - context parameter in constructor is not accepting

I am trying to make a generic method using Android DatePickerDialog , so instead of using DatePickerDialog everytime it will be called through a generic function and return the date. It may be part of customized component component as well (i.e. LinearLayout or NavigationView ).

However I am stuck due to context parameter in the constructor of DatePickerDialog . It insist actual activity class name , and I am something looking like parameter ie getContext(), getApplicationContext() etc..

Working but can't be used in generic method -

DatePickerDialog datePickerDialog = new DatePickerDialog(RecordActivity3.this, new DatePickerDialog.OnDateSetListener() {


Not working -
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {


Not working -
DatePickerDialog datePickerDialog = new DatePickerDialog(getApplicationContext(), new DatePickerDialog.OnDateSetListener() {


Not working -
DatePickerDialog datePickerDialog = new DatePickerDialog(activityClassParamter, new DatePickerDialog.OnDateSetListener() {


Please suggest in case you have worked on similar problem..

Answer

You need activity context for dialog. Dialog will not work with application context. You can read more about context here.

Declare activity parameter in your generic dialog function and use it as context.

... genericDialog(Activity activity) {
   ... new DatePickerDialog(activity /* note activity context here*/ , ....);
}

If you are calling this from an activity, you can just call it like

 genericDialog(ActivityClassName.this /* reference to activity */)
Comments