I used DatePickerDialog with the code below. I retrieve the date of birth of the user in my database and when I open the dateDialog it supposed to be the user’s date of birth. But when it supposed to be September, it ended up as October. Any idea what causes this and how to fix it?
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
break;
}
}
private void updateDisplay() {
dateText.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth +1).append("/")
.append(mDay).append("/")
.append(mYear).append(" "));
}
DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
dob1 = (monthOfYear + "/" + dayOfMonth + "/" + year);
if(maxYear - mYear <= 12){
alertMessage = "User must be above age of 12.";
dialogBox();
year = mYear;
}
else{
updateDisplay();
}
}
};
Based on comments, it seems you’re storing the value as a 1-based index. (Since September is 9, as you said, that means January is 1.) You need to pass in the 0-based index to the
DatePickerDialog. Simply subtract 1 from your value when it’s passed into the constructor (assuming that’s where you pull it from the database).