Saturday, February 27, 2016

Calculate Age from Date of Birth (Java/Android SourceCode)

Here is the concept for calculating Age from a user defined or selected Date of Birth. I've used Ecplise IDE to develop an android application. But, the MainActivity.class source code can also be used in Java.

Steps in Android:

A. Create XML layout with
  • DataPicker (pre-defined data object)
  • Button (onClick that will handle setting values within respective text view objects)
  • TextView (object to get DOB)
  • TextView (object to show Age)
B. Create Package-Class called MainActivity

0. Import the necessary widgets
  • import java.util.Calendar;
  • import android.app.Activity;
  • import android.os.Bundle;
  • import android.view.Menu;
  • import android.view.View;
  • import android.view.View.OnClickListener;
  • import android.widget.Button;
  • import android.widget.DatePicker;
  • import android.widget.TextView;
  • import com.example.datedemo.R;
1. Initiate DataPicker, TextView elements by importing declaring and importing pre-defined respective classes
  •  DatePicker picker;
  • TextView tvdob;
  • TextView tvage;
2. Override onCreate bundle and setContentView
  • setContentView(R.layout.date);
3. Allocate Memory for initiated objects within onCreate bundle
  • btnsubmit=(Button)findViewById(R.id.button1);
  • picker =(DatePicker) findViewById(R.id.datePicker1);
  • tvdob=(TextView)findViewById(R.id.tvdob);
  • tvage=(TextView)findViewById(R.id.tvage);


  • 4. Create OnClick event handler within onCreate bundle
  • btnsubmit.setOnClickListener(new OnClickListener() {
  • @Override
    public void onClick(View view) {
    // TODO Auto-generated method stub
    //getDateofBirth() receives values from the custom method declared public below
    tvdob.setText(getDateofBirth());
    //currentDate() receives values from the custom method declared public below
    tvage.setText(currentDate());

    }
    });
    5. Create custom method to receive Date of Birth from the picker object values selected:
    • public String getDateofBirth(){
      StringBuilder builder=new StringBuilder();
    builder.append("DOB: ");
    builder.append((picker.getMonth() + 1)+"/");//month is 0 based
    builder.append(picker.getDayOfMonth()+"/");
    builder.append(picker.getYear());
    return builder.toString();
        }
    5. Create custom method to receive Current Date Values from Calendar Object (CALENDAR WIDGET SHOULD BE IMPORTED):
    • public String currentDate(){
    StringBuilder todaydate=new StringBuilder();
    //get today's date
    Calendar today=Calendar.getInstance();
    //calculate age by subtracting today's date year from the user's (picker object) selected date year 
    int age=today.get(Calendar.YEAR)-picker.getYear();
    if (today.get(Calendar.MONTH) < picker.getYear()) {
     age--;  
    } else if (today.get(Calendar.MONTH) == picker.getYear()
       && today.get(Calendar.DAY_OF_MONTH) < picker.getYear()) {
     age--;  
    }
    todaydate.append("Age: ");
    todaydate.append(String.valueOf(age));
    return todaydate.toString();
    }
    C. Declare the manifest file with the the and details.
    D. Run the application and sip on a cup of coffee, while you take pride in the new bit code you executed and learnt :-)

    ________________________________________________________

    Just in case, the lazy boy in you wants just to copy/paste the code and perform a quick fix, here following is the full source code for MainActivity.class:

    //source beings here
    package com.datepick; //your Gen package name

    import java.util.Calendar;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.DatePicker;
    import android.widget.TextView;

    import com.example.datedemo.R; //your package name

    public class MainActivity extends Activity{
    //Create Instance 
    DatePicker picker;
    TextView tvdob;
    TextView tvage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.date);
    //Allocate memory
    Button btnsubmit=(Button)findViewById(R.id.button1);
    picker =(DatePicker) findViewById(R.id.datePicker1);
    tvdob=(TextView)findViewById(R.id.tvdob);
    tvage=(TextView)findViewById(R.id.tvage);
    btnsubmit.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
    // TODO Auto-generated method stub
    tvdob.setText(getDateofBirth());
    tvage.setText(currentDate());
    }
    });
    }
    public String getDateofBirth(){
      StringBuilder builder=new StringBuilder();
    builder.append("DOB: ");
    builder.append((picker.getMonth() + 1)+"/");//month is 0 based
    builder.append(picker.getDayOfMonth()+"/");
    builder.append(picker.getYear());
    return builder.toString();
        }
    public String currentDate(){
    StringBuilder todaydate=new StringBuilder();
    Calendar today=Calendar.getInstance();
    int age=today.get(Calendar.YEAR)-picker.getYear();
    if (today.get(Calendar.MONTH) < picker.getYear()) {
     age--;  
    } else if (today.get(Calendar.MONTH) == picker.getYear()
       && today.get(Calendar.DAY_OF_MONTH) < picker.getYear()) {
     age--;  
    }
    todaydate.append("Age: ");
    todaydate.append(String.valueOf(age));
    return todaydate.toString();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
    }

    }
    //Code Ends

    Make sure to create xml layout elements and Manifest file declarations before running the application.