I’m new to android and I admit I don’t fully understand what context is as it applies to Android. I understand a little, but not fully. I’m trying to modify an Android Datepicker so that only the day and month are in the DatePickerDialog. I asked stackoverflow and I was given one answer in the form of three code blocks. The code is below. My problem is I’m getting one error at
mDialog = new CustomDPDialog(getContext(), this,… the error is at getContext(). It says that getContext() is undefined for the onClickListener. So, looking at the below code, what would be the fix for getContext()? Creating a getContext() method actually breaks the code worse. And using context, null in place of getContext(), this, erases the error, but it shouldn’t be null, it should be this.
static final int ID_DATEPICKER = 0;
private int myYear, myMonth, myDay;
TextView dateDisplay;
Dialog mDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dateDisplay = (TextView)findViewById(R.id.dateDisplay);
Button datePickerButton = (Button)findViewById(R.id.datepickerbutton);
datePickerButton.setOnClickListener(datePickerButtonOnClickListener);
}
private Button.OnClickListener datePickerButtonOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
mDialog = new CustomDPDialog(getContext(), this,
c.get(Calendar.YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
mDialog.show();
DatePicker dp = findDatePicker((ViewGroup) mDialog.getWindow().getDecorView());
if (dp != null) {
((ViewGroup) dp.getChildAt(0)).getChildAt(0).setVisibility(View.GONE);
}
}
class CustomDPDialog extends DatePickerDialog {
public CustomDPDialog(Context context,
OnDateSetListener callBack, int myYear, int myMonth,
int myDay) {
super(context, callBack, myYear, myMonth, myDay);
}
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
super.onDateChanged(view, year, month, day);
mDialog.setTitle((month + 1) + "-" + day + "-");
}
}
private DatePicker findDatePicker(ViewGroup group) {
if (group != null) {
for (int i = 0, j = group.getChildCount(); i < j; i++) {
View child = group.getChildAt(i);
if (child instanceof DatePicker) {
return (DatePicker) child;
} else if (child instanceof ViewGroup) {
DatePicker result = findDatePicker((ViewGroup) child);
if (result != null)
return result;
}
}
}
return null;
}
};
}
try
or
I recommend the first since getApplicationContext() can sometimes cause problems