Age Calculator using DatePickerDialog



Here we will create a simple app which calculates the Age of an individual whose date of birth is provided. This app will use a DatePickerDialog for selecting the date of birth.

Step 1: Create a new project with name ‘Age Calculator’ and package name com.myexample.appcompat.age. Fill the forms and click “Finish” button.

Step 2: In app level build.gradle add following dependencies:

dependencies {
	compile fileTree(dir: 'libs', include: ['*.jar'])
	compile 'com.android.support:appcompat-v7:27.0.2'
	compile 'com.android.support:design:27.0.2'
	compile 'com.android.support:support-v4:27.0.2'
}

Step 3: In drawable folder add image of a Calendar icon ‘calendar.png’.

Step 4: Open res -> layout -> xml (or) main.xml and add codes for displaying 2 EditText, an ImageView, and
a Button.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	tools:context=".MainActivity">

	<ScrollView
		android:id="@+id/vscroll1"
		android:layout_width="match_parent"
		android:layout_height="match_parent">

		<LinearLayout
			android:id="@+id/linear1"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:background="#FFFFFF"
			android:orientation="vertical">

			<LinearLayout
				android:id="@+id/linear4"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:padding="8dp"
				android:orientation="horizontal">

				<TextView
					android:id="@+id/textview2"
					android:layout_width="wrap_content"
					android:layout_height="wrap_content"
					android:padding="8dp"
					android:text="Date of Birth:"
					android:textSize="18sp"
					android:textColor="#37474F"
					android:layout_weight="1"/>

				<EditText
					android:id="@+id/edittext1"
					android:layout_width="120dp"
					android:layout_height="wrap_content"
					android:layout_margin="8dp"
					android:padding="8dp"
					android:background="#B2DFDB"
					android:textSize="16sp"
					android:textColor="#000000"
					android:hint="Click here--"
					android:textColorHint="#607D8B"
					android:enabled="false"/>

				<ImageView
					android:id="@+id/imageview1"
					android:layout_width="40dp"
					android:layout_height="40dp"
					android:layout_margin="8dp"
					android:src="@drawable/calendar"
					android:scaleType="fitXY"/>

			</LinearLayout>

			<LinearLayout
				android:id="@+id/linear6"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:padding="8dp"
				android:orientation="horizontal">

				<TextView
					android:id="@+id/textview4"
					android:layout_width="wrap_content"
					android:layout_height="wrap_content"
					android:padding="8dp"
					android:text="Age:"
					android:textSize="18sp"
					android:textColor="#37474F"/>

				<EditText
					android:id="@+id/edittext2"
					android:layout_width="match_parent"
					android:layout_height="wrap_content"
					android:padding="8dp"
					android:background="#B2DFDB"
					android:textSize="18sp"
					android:textColor="#000000"
					android:textColorHint="#607D8B"
					android:enabled="false"/>

			</LinearLayout>

			<LinearLayout
				android:id="@+id/linear7"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:padding="8dp"
				android:orientation="horizontal">

				<Button
					android:id="@+id/button2"
					android:layout_width="match_parent"
					android:layout_height="wrap_content"
					android:padding="8dp"
					android:background="#00BFA5"
					android:text="Reset"
					android:textSize="18sp"
					android:textStyle="bold"
					android:textColor="#000000"/>

			</LinearLayout>

		</LinearLayout>

	</ScrollView>

</RelativeLayout>		

Step 5: Open app -> java -> package and open MainActivity.java. Add following code in it.

package com.myexample.appcompat.age;

import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.support.v7.app.AppCompatActivity;
import android.widget.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class MainActivity extends AppCompatActivity {
	// Declare all EditText, ImageView and Buttons
	private ImageView imageview1;
	private EditText edittext1;
	private EditText edittext2;
	private Button button2;
	
	@Override
	protected void onCreate(Bundle _savedInstanceState) {
		super.onCreate(_savedInstanceState);
		setContentView(R.layout.main);
		initialize();
	}
	
	private void initialize() {
		edittext1 = (EditText) findViewById(R.id.edittext1);
		imageview1 = (ImageView) findViewById(R.id.imageview1);
		edittext2 = (EditText) findViewById(R.id.edittext2);
		button2 = (Button) findViewById(R.id.button2);
		
		// Show DatePickerDialog when imageview1 is clicked.
		imageview1.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					showDatePickerDialog(imageview1);
				}
			});
			
		// Empty all EditText when Reset button is clicked.
		button2.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					edittext1.setText("");
					edittext2.setText("");
				}
			});

	}
	
	// Define showDatePickerDialog(View).
	public void showDatePickerDialog(View v) {
		// Create and show a new DatePickerFragment.
		DialogFragment newFragment = new DatePickerFragment();
		newFragment.show(getFragmentManager(), "datePicker");
	}

	// Define a DialogFragment class DatePickerFragment.
	public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
		// Define a new Calendar for current date
		Calendar now = Calendar.getInstance();
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Create DatePickerFragment (a DialogFragment) with a new DatePickerDialog
			int y = now.get(Calendar.YEAR);
			int m = now.get(Calendar.MONTH);
			int d = now.get(Calendar.DAY_OF_MONTH);
// Current day of month, month, and year are set as the day, month, and year of this DatePickerDialog.
			return new DatePickerDialog(getActivity(), this, y, m, d);
		}
		// When Date of birth is selected
		public void onDateSet(DatePicker view, int year, int month, int day) {
			int mon = month +1;
			// Define a new Calendar for birth date.
			Calendar birthDay = Calendar.getInstance();		
			String date = day + "/" + mon + "/" + year;
			// Define the 2 EditText again using their IDs in main.xml.
			EditText edittext21 = getActivity().findViewById(R.id.edittext1);
			EditText edittext22 = getActivity().findViewById(R.id.edittext2);
			edittext21.setText(date);
			// Set the selected year, month, and day as the year, month, and day of Calendar birthDay.
			birthDay.set(Calendar.YEAR, year);
			birthDay.set(Calendar.MONTH, month);
			birthDay.set(Calendar.DAY_OF_MONTH, day);
			// find difference between present date and selected date in milliseconds.
			double diff = (long)(now.getTimeInMillis() - birthDay.getTimeInMillis());
			// If difference is less than 0, show message that selected date is in future.
			if (diff < 0) {
				Toast.makeText(getContext(), "Selected date is in future.", Toast.LENGTH_SHORT).show();
				edittext22.setText("");
			}
			else {
				// Get difference between years
				int years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
				int currMonth = now.get(Calendar.MONTH) + 1;
				int birthMonth = birthDay.get(Calendar.MONTH) + 1;
				
				// Get difference between months
				int months = currMonth - birthMonth;
				
				// If month difference is negative then reduce years by one 
				// and calculate the number of months.
				if (months < 0){
					years--;
					months = 12 - birthMonth + currMonth;
					if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
						months--;
				} else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
				{
					years--;
					months = 11;
				}

				// Calculate the days
				int days = 0;
				if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
					days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
				else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
				{
					int today = now.get(Calendar.DAY_OF_MONTH);
					months--;
					days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
				} 
				else
				{
					days = 0;
					if (months == 12)
					{
						years++;
						months = 0;
					}
				}		
				// Display the age in years, months and days
				edittext22.setText(years + " years, " + months + " months, " + days + " days");
			}
		}

	}
		
}

Output:
Now run the app. If you click on the ImageView it will display the DatePickerDialog from which date of birth can be selected. On selecting the date of birth, it calculates and displays the present age in years, months, and days.