I am new to android development and I'm trying to develop an age calculator. With my current code I'm able to find the difference between years and months correctly but the days are not correct. I know I'm doing something wrong. But I'm not able to figure it out. I also used jodatime api, but when I used it my app closed when I call this function I am not able to understand what I am doing wrong. My code is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDateDisplay = (TextView) findViewById(R.id.showMyDate);
mPickDate = (Button) findViewById(R.id.myDatePickerButton);
mPickDate.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
dob_Year = c.get(Calendar.YEAR);
dob_Month = c.get(Calendar.MONTH);
dob_Day = c.get(Calendar.DAY_OF_MONTH);
// display the current date
updateDisplay();
}
private void updateAge()
{
current_Year = c.get(Calendar.YEAR);
current_Month = c.get(Calendar.MONTH);
current_Day = c.get(Calendar.DAY_OF_YEAR);
if (current_Day < dob_Day) {
current_Month--;
current_Day+=c.getMaximum(dob_Month);
}
if (current_Month < dob_Month) {
current_Year--;
current_Month += 12;
}
int ageYear=current_Year-dob_Year;
int ageMonths=current_Month-dob_Month;
int ageDays= current_Day-dob_Day;
this.mAgeDisplay.setText(
new StringBuilder()
.append(ageYear).append(" Years ")
.append(ageMonths).append(" Months ")
.append(ageDays).append(" Days "));
}
private void updateDisplay() {
this.mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(dob_Day).append("-")
.append(dob_Month + 1).append("-")
.append(dob_Year).append(" "));
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
dob_Year = year;
dob_Month = monthOfYear;
dob_Day = dayOfMonth;
updateDisplay();
updateAge();
}
};
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
dob_Year, dob_Month, dob_Day);
}
return null;
}
In this code fragment dob_ variables get their values from datepicker.