Android Age Calculator Application Example

In this tutorial we are going to create an Android Age Calculator Application from start to finish. If you have not heard of android age calculator, it is a simple calculator that you can use to calculate how many days or months you have to your next birthday. You can as well use it to find out which day your next birthday falls in.

You can search Google Play with the keyword age calculator to see many examples of age calculator apps published on Google Play.

For this android application, we will make use of TextView controls for displaying text content, a date picker widget that will afford our app users the opportunity to choose a date from a calendar.

Finally, we will use two Button View controls for calculation and to reset previously displayed results.

Right now it is important for us to understand what we are planning to achieve in this tutorial. The screen-shot of our project is shown below.

Android Age Calculator

Before we start, it is important for you to understand the tools and environment I used in this android tutorial. Feel free to use tools you are familiar with.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidAgeCalculator

Package: com.inducesmile.androidagecalculator

Select Blank Activity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

If you are using Android Studio as your choice IDE, the new project will create a default
MainActivity.java file and its corresponding layout file.

The default layout file is the activity_main.xml. Open you layout file and add all the required View components that we need. The code sample for our layout file is as shown below.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/icons">
    <ScrollView
        android:id="@+id/scroll_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_above="@+id/display_date_result"
        android:layout_marginBottom="6dp"
        android:background="#ffffff"
        android:scrollbars="none">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:id="@+id/current_date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="12dp"
                android:layout_alignParentTop="true"
                android:text="@string/date_today"
                android:textStyle="bold"
                android:textSize="16sp"
                android:background="@color/primary_light"
                android:textColor="@color/primary_text" />
            <LinearLayout
                android:id="@+id/first_layout_wrapper"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/current_date"
                android:padding="8dp"
                android:background="@drawable/border_colour"
                android:orientation="horizontal">
                <TextView
                android:id="@+id/display_today_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="12dp"
                android:text="@string/display_date"
                android:textStyle="bold"
                android:textSize="16sp"
                android:layout_weight="1"
                android:textColor="@color/primary_text" />
                <ImageView
                    android:id="@+id/set_date_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:contentDescription="@string/app_name"
                    android:layout_weight="1"
                    android:layout_gravity="right|center_vertical"
                    android:src="@drawable/dateicon"/>
            </LinearLayout>
            <TextView
                android:id="@+id/birthday_date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="12dp"
                android:layout_below="@+id/first_layout_wrapper"
                android:layout_marginTop="32dp"
                android:text="@string/birthday_date"
                android:textStyle="bold"
                android:textSize="16sp"
                android:background="@color/primary_light"
                android:textColor="@color/primary_text" />
            <LinearLayout
                android:id="@+id/second_layout_wrapper"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/birthday_date"
                android:padding="8dp"
                android:background="@drawable/border_colour"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/display_birthday_date"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="12dp"
                    android:text="@string/display_date"
                    android:textStyle="bold"
                    android:textSize="16sp"
                    android:layout_weight="1"
                    android:textColor="@color/primary_text" />
                <ImageView
                    android:id="@+id/set_birthday_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:contentDescription="@string/app_name"
                    android:layout_weight="1"
                    android:layout_gravity="right|center_vertical"
                    android:padding="0dp"
                    android:layout_margin="0dp"
                    android:src="@drawable/dateicon"/>
            </LinearLayout>
            <LinearLayout
                android:id="@+id/button_wrapper"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/second_layout_wrapper"
                android:layout_marginTop="32dp"
                android:orientation="horizontal">
                <Button
                    android:id="@+id/button_calculate"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center|center_horizontal"
                    android:padding="16dp"
                    android:text="@string/calculation_text"
                    android:layout_marginRight="1dp"
                    android:background="@color/primary_dark"
                    android:layout_weight="1"/>
                <Button
                    android:id="@+id/button_clear"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center|center_horizontal"
                    android:padding="16dp"
                    android:layout_marginLeft="1dp"
                    android:text="@string/clear_results"
                    android:background="@color/primary_dark"
                    android:layout_weight="1"/>
            </LinearLayout>
            <TextView
                android:id="@+id/age_header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="12dp"
                android:layout_below="@+id/button_wrapper"
                android:layout_marginTop="32dp"
                android:text="@string/current_age"
                android:textStyle="bold"
                android:textSize="16sp"
                android:background="@color/primary_light"
                android:textColor="@color/primary_text" />
            <TableLayout
                android:id="@+id/age_table"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/age_header">
                <TableRow
                    android:background="@drawable/border_colour"
                    android:padding="24dp">
                    <TextView
                        android:id="@+id/years_in_age"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center|center_horizontal"
                        android:text="@string/years_number"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/months_in_age"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center|center_horizontal"
                        android:text="@string/months_number"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/days_in_age"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center|center_horizontal"
                        android:text="@string/days_number"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </TableRow>
            </TableLayout>
            <TextView
                android:id="@+id/next_birthday_header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="12dp"
                android:layout_below="@+id/age_table"
                android:layout_marginTop="32dp"
                android:text="@string/next_birthday"
                android:textStyle="bold"
                android:textSize="16sp"
                android:background="@color/primary_light"
                android:textColor="@color/primary_text" />
            <TableLayout
                android:id="@+id/next_age_table"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/next_birthday_header">
                <TableRow
                    android:background="@drawable/border_colour"
                    android:padding="24dp">
                    <TextView
                        android:id="@+id/years_in_birthday"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center|center_horizontal"
                        android:text="@string/years_number"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/months_in_birthday"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center|center_horizontal"
                        android:text="@string/months_number"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/days_in_birthday"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="center|center_horizontal"
                        android:text="@string/days_number"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </TableRow>
            </TableLayout>
            <TextView
                android:id="@+id/age_analysis"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="12dp"
                android:layout_below="@+id/next_age_table"
                android:layout_marginTop="32dp"
                android:text="@string/age_analysis"
                android:textStyle="bold"
                android:textSize="16sp"
                android:background="@color/primary_light"
                android:textColor="@color/primary_text" />
            <TableLayout
                android:id="@+id/extra_information"
                android:layout_width="match_parent"
                android:layout_below="@+id/age_analysis"
                android:layout_marginTop="24dp"
                android:paddingLeft="24dp"
                android:paddingRight="24dp"
                android:layout_height="wrap_content">
                <TableRow android:padding="8dp">
                    <TextView
                        android:id="@+id/total_years"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:textSize="16dp"
                        android:textStyle="bold"
                        android:textColor="@color/primary_text"
                        android:gravity="left"
                        android:text="@string/total_years"/>
                    <TextView
                        android:id="@+id/total_years_result"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:textSize="16dp"
                        android:textStyle="bold"
                        android:textColor="@color/primary_text"
                        android:gravity="left"
                        android:text="@string/zero"/>
                </TableRow>
                <TableRow android:padding="8dp">
                    <TextView
                        android:id="@+id/total_months"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:textSize="16dp"
                        android:textStyle="bold"
                        android:textColor="@color/primary_text"
                        android:gravity="left"
                        android:text="@string/total_months"/>
                    <TextView
                        android:id="@+id/total_months_result"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:textSize="16dp"
                        android:textStyle="bold"
                        android:textColor="@color/primary_text"
                        android:gravity="left"
                        android:text="@string/zero"/>
                </TableRow>
                <TableRow android:padding="8dp">
                    <TextView
                        android:id="@+id/total_weeks"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/total_months"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/total_weeks_result"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/zero"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </TableRow>
                <TableRow android:padding="8dp">
                    <TextView
                        android:id="@+id/total_days"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/total_days"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/total_days_result"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/zero"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </TableRow>
                <TableRow android:padding="8dp">
                    <TextView
                        android:id="@+id/total_hours"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/total_hours"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/total_hours_result"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/zero"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </TableRow>
                <TableRow android:padding="8dp">
                    <TextView
                        android:id="@+id/total_minutes"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/total_minutes"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/total_minutes_result"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/zero"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </TableRow>
                <TableRow android:padding="8dp">
                    <TextView
                        android:id="@+id/total_seconds"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/total_seconds"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                    <TextView
                        android:id="@+id/total_seconds_result"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:gravity="left"
                        android:text="@string/zero"
                        android:textColor="@color/primary_text"
                        android:textSize="16dp"
                        android:textStyle="bold" />
                </TableRow>
            </TableLayout>
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>

 

The layout file might be big but it is simple. It is a combination of TableLayout, LinearLayout and other View controls as mentioned before.

Next, we will move over to our project MainActivity.java file. In the MainActivity class, the instances of some of our View controls are obtained. As seen on the app interface, we have added two DatePicker widgets. A click event listener is attached to the datepicker so that the date selected can be assigned to a date object.

The same approach was used for the Button View controls. Most of the age calculation is done when the calculate button is clicked.

Adding and subtracting date in java can be tricky if you are using Java built-in Date API. For that reason, we will make use of a Java third party library for time called Joda Time. You can read more about this awesome Java library here.

For us to make use of this library in our project, we will add this line of code in the dependency section of our project build.gradle file.

compile 'joda-time:joda-time:2.9.1'

Thereafter, we will sync our project in order to download this library and make it available in our project.

The code for our MainActivity class is shown below.

MainActivity.java

package com.inducesmile.completecalculatorapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.Weeks;
import java.util.Calendar;
public class AgeCalculatorFragment extends Fragment {
    private TextView todayDate;
    private ImageView todayDateSelector;
    private DatePicker todayDateDialog;
    private TextView yourBirthdayDate;
    private ImageView yourBirthdayDateSelector;
    private int year;
    private int month;
    private int day;
    public static final int DATE_PICKER_FRAGMENT = 1;
    public static final int SECOND_DATE_PICKER_FRAGMENT = 2;
    private TextView currentBirthdayYear;
    private TextView currentBirthdayMonth;
    private TextView currentBirthdayDay;
    private TextView nextBirthdayYear;
    private TextView nextBirthdayMonth;
    private TextView nextBirthdayDay;
    private TextView totalYearResult;
    private TextView totalMonthResult;
    private TextView totalWeekResult;
    private TextView totalDayResult;
    private TextView totalHourResult;
    private TextView totalMinuteResult;
    private TextView totalSecondResult;
    public AgeCalculatorFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_age_calculator, container, false);
        ((AppCompatActivity) getActivity()).getSupportActionBar().show();
        currentBirthdayYear = (TextView)view.findViewById(R.id.years_in_age);
        currentBirthdayMonth = (TextView)view.findViewById(R.id.months_in_age);
        currentBirthdayDay = (TextView)view.findViewById(R.id.days_in_age);
        nextBirthdayYear = (TextView)view.findViewById(R.id.years_in_birthday);
        nextBirthdayMonth = (TextView)view.findViewById(R.id.months_in_birthday);
        nextBirthdayDay = (TextView)view.findViewById(R.id.days_in_birthday);
        totalYearResult = (TextView)view.findViewById(R.id.total_years_result);
        totalMonthResult = (TextView)view.findViewById(R.id.total_months_result);
        totalWeekResult = (TextView)view.findViewById(R.id.total_weeks_result);
        totalDayResult = (TextView)view.findViewById(R.id.total_days_result);
        totalHourResult = (TextView)view.findViewById(R.id.total_hours_result);
        totalMinuteResult = (TextView)view.findViewById(R.id.total_minutes_result);
        totalSecondResult = (TextView)view.findViewById(R.id.total_seconds_result);
        todayDate = (TextView)view.findViewById(R.id.display_today_date);
        todayDateSelector = (ImageView)view.findViewById(R.id.set_date_icon);
        yourBirthdayDate = (TextView)view.findViewById(R.id.display_birthday_date);
        yourBirthdayDateSelector = (ImageView)view.findViewById(R.id.set_birthday_icon);
        Button calculateButton = (Button)view.findViewById(R.id.button_calculate);
        Button clearButton = (Button)view.findViewById(R.id.button_clear);
        todayDate.setText(setCurrentDateOnView());
        yourBirthdayDate.setText(setCurrentDateOnView());
        todayDateSelector.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerFragment datePickerDialog = new DatePickerFragment();
                datePickerDialog.setTargetFragment(AgeCalculatorFragment.this, DATE_PICKER_FRAGMENT);
                datePickerDialog.show(getFragmentManager(), "DATE TODAY");
            }
        });
        yourBirthdayDateSelector.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerFragment datePickerDialog = new DatePickerFragment();
                datePickerDialog.setTargetFragment(AgeCalculatorFragment.this, SECOND_DATE_PICKER_FRAGMENT);
                datePickerDialog.show(getFragmentManager(), "BIRTHDAY TODAY");
            }
        });
        calculateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getTodayDate = todayDate.getText().toString();
                String getBirthdayDate = yourBirthdayDate.getText().toString();
                DateTime todayDateTime = convertToDateTime(getTodayDate);
                DateTime birthdayDateTime = convertToDateTime(getBirthdayDate);
                displayCurrentBirthday(todayDateTime, birthdayDateTime);
                displayNextBirthday(todayDateTime, birthdayDateTime);
                displayAgeAnalysis(todayDateTime, birthdayDateTime);
            }
        });
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentBirthdayDay.setText(Html.fromHtml("<h4>Days</h4>"));
                currentBirthdayMonth.setText(Html.fromHtml("<h4>Months</h4>"));
                currentBirthdayYear.setText(Html.fromHtml("<h4>Years</h4>"));
                nextBirthdayDay.setText(Html.fromHtml("<h4>Days</h4>"));
                nextBirthdayMonth.setText(Html.fromHtml("<h4>Months</h4>"));
                nextBirthdayYear.setText(Html.fromHtml("<h4>Years</h4>"));
                totalDayResult.setText("");
                totalWeekResult.setText("");
                totalMonthResult.setText("");
                totalYearResult.setText("");
                totalHourResult.setText("");
                totalMinuteResult.setText("");
                totalSecondResult.setText("");
            }
        });
        return view;
    }
    private void displayAgeAnalysis(DateTime dateToday, DateTime birthdayDate){
        Period dateDifferencePeriod = displayBirthdayResult(dateToday, birthdayDate);
        int getDateInDays = dateDifferencePeriod.getDays();
        int getDateInWeeks = Weeks.weeksBetween(new DateTime(birthdayDate), new DateTime(dateToday)).getWeeks();;
        int getDateInMonths = dateDifferencePeriod.getMonths();
        int getDateInYears = dateDifferencePeriod.getYears();
        int mDay = getDateInWeeks * 7;
        int mMonth = getDateInMonths + (getDateInYears * 12);
        int hours = mDay * 24;
        int minutes = mDay * 24 * 60;
        int seconds = mDay * 24 * 60 * 60;
        totalDayResult.setText(Html.fromHtml(String.valueOf(mDay)));
        totalWeekResult.setText(Html.fromHtml(String.valueOf(getDateInWeeks)));
        totalMonthResult.setText(Html.fromHtml(String.valueOf(mMonth)));
        totalYearResult.setText(Html.fromHtml(String.valueOf(getDateInYears)));
        totalHourResult.setText(Html.fromHtml(String.valueOf(hours)));
        totalMinuteResult.setText(Html.fromHtml(String.valueOf(minutes)));
        totalSecondResult.setText(Html.fromHtml(String.valueOf(seconds)));
    }
    private void displayNextBirthday(DateTime dateToday, DateTime birthdayDate){
        Calendar mCalendar = Calendar.getInstance();
        int year = mCalendar.get(Calendar.YEAR);
        DateTime nextBirthday = birthdayDate.withYear(year);
        Toast.makeText(getActivity(), "Birthday " + nextBirthday.getYear(), Toast.LENGTH_LONG).show();
        Period dateDifferencePeriod = displayBirthdayResult(nextBirthday, dateToday);
        int getDateInDays = dateDifferencePeriod.getDays();
        int getDateInMonths = dateDifferencePeriod.getMonths();
        int getDateInYears = dateDifferencePeriod.getYears();
        nextBirthdayDay.setText(Html.fromHtml("<h4>Days</h4>" + getDateInDays));
        nextBirthdayMonth.setText(Html.fromHtml("<h4>Months</h4>" + getDateInMonths));
        nextBirthdayYear.setText(Html.fromHtml("<h4>Years</h4>" + getDateInYears));
    }
    private void displayCurrentBirthday(DateTime dateToday, DateTime birthdayDate){
        Period dateDifferencePeriod = displayBirthdayResult(dateToday, birthdayDate);
        int getDateInDays = dateDifferencePeriod.getDays();
        int getDateInMonths = dateDifferencePeriod.getMonths();
        int getDateInYears = dateDifferencePeriod.getYears();
        currentBirthdayDay.setText(Html.fromHtml("<h4>Days</h4>" + getDateInDays));
        currentBirthdayMonth.setText(Html.fromHtml("<h4>Months</h4>" + getDateInMonths));
        currentBirthdayYear.setText(Html.fromHtml("<h4>Years</h4>" + getDateInYears));
    }
    private Period displayBirthdayResult(DateTime dateToday, DateTime birthdayDate){
        Period dateDifferencePeriod = new Period(birthdayDate, dateToday, PeriodType.yearMonthDayTime());
        return dateDifferencePeriod;
    }
    private DateTime convertToDateTime(String stringToConvert){
        String[] newStringArray = convertStringToArray(stringToConvert);
        int year = Integer.parseInt(newStringArray[2].trim());
        int day = Integer.parseInt(newStringArray[1].trim());
        int month = Integer.parseInt(newStringArray[0].trim());
        LocalDate mLocalDate = new LocalDate(year, month, day);
        DateTime firstDateTime = mLocalDate.toDateTime(LocalTime.fromDateFields(mLocalDate.toDate()));
        return firstDateTime;
    }
    private String[] convertStringToArray(String stringToConvert){
        String[] newStringArray = stringToConvert.split("-");
        return newStringArray;
    }
    public String setCurrentDateOnView() {
        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        StringBuilder displayStringBuilder = new StringBuilder().append(month + 1).append("-").append(day).append("-").append(year).append(" ");
        return displayStringBuilder.toString();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
            case DATE_PICKER_FRAGMENT:
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String resultDate = bundle.getString("RETURNED_DATE", "error");
                    todayDate.setText(resultDate);
                }
                break;
            case SECOND_DATE_PICKER_FRAGMENT:
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String resultDate = bundle.getString("RETURNED_DATE", "error");
                    yourBirthdayDate.setText(resultDate);
                }
                break;
            }
        }
    }

 

Add the DatePickerFragment class below

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

import java.util.Calendar;

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, year, month + 1, day);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        int mYear = year;
        int mMonth = monthOfYear + 1;
        int mDay = dayOfMonth;

        String selectedDate = dayOfMonth + " - " + mMonth + " - " + year;
        //Toast.makeText(getActivity(), "Selected " + selectedDate, Toast.LENGTH_LONG).show();
        Intent i = new Intent();
        i.putExtra("RETURNED_DATE",selectedDate);
        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
    }
}

There are few private methods created for this project so that our code can be readable. If you have any question about this code, kindly let me know.

This brings us to the end of this tutorial, If you find anything confusing kindly contact me with your questions or use the comment box below.

Now, when you run your application you will see the interface that looks similar to the sample that was shown earlier on.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive our new post once it is published.

You can see a working version of this age calculator in my android app – Daily Pocket Calculator – in Google Play Store.

Download it and let me know what you think about it.

18 Comments

    • Inducesmile
    • Inducesmile
    • Inducesmile

Add a Comment