Skip to main content

AGE CALCULATOR - ANDROID

In this Android tutorial let us learn about how to create a nice small Android app which will help you to find out your age by year, month and days.




Above screen shows the simple layout of an age calculator application, here select your date of birth by touch the Date of Birth button. Now the screen will looks like below




Now your age got calculated and display in result field and also pop up as toast as given below




Now follow the coding to develop this simple application

1. Age Calculator Layout (mainactivity.xml)



<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"
    android:background="@color/whatzappBorder" >
//apply your favourite color 
    
    <Button
        android:id="@+id/button1"
        style="@style/Btn"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:text="Date Of Birth" />
//apply your button style

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:textColor="@color/golden"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="23dp"
        android:text="Current Date"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textColor="@color/golden"
        android:layout_marginTop="18dp"
        android:text="Birth Date"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textColor="@color/golden"
        android:layout_marginTop="16dp"
        android:text="Result"
        android:textStyle="bold" />

</RelativeLayout>



2. Main Class ( MainActivity.java)



public class MainActivity extends Activity implements OnClickListener {

private Button btnStart;
static final int DATE_START_DIALOG_ID = 0;
private int startYear = 1900;
private int startMonth = 6;
private int startDay = 15;
private AgeCalculation age = null;
private TextView currentDate;
private TextView birthDate;
private TextView result;
StringTokenizer tok;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
age = new AgeCalculation();
currentDate = (TextView) findViewById(R.id.textView1);
currentDate.setText("Current Date(DD/MM/YY) : " + age.getCurrentDate());
birthDate = (TextView) findViewById(R.id.textView2);
result = (TextView) findViewById(R.id.textView3);
btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(this);

}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_START_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, startYear,
startMonth, startDay);
}
return null;
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
startYear = selectedYear;
startMonth = selectedMonth;
startDay = selectedDay;
age.setDateOfBirth(startYear, startMonth, startDay);
birthDate.setText("Date of Birth(DD/MM/YY): " + selectedDay + ":"
+ (startMonth + 1) + ":" + startYear);
calculateAge();
}
};

public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
showDialog(DATE_START_DIALOG_ID);
break;

default:
break;
}
}

private void calculateAge() {
age.calcualteYear();
age.calcualteMonth();
age.calcualteDay();
String aggg;

aggg = age.getResult();
//Tokenizer
tok = new StringTokenizer(aggg, ":");

String dat1 = tok.nextToken();
String mon1 = tok.nextToken();
String year1 = tok.nextToken();

Toast.makeText(
getBaseContext(),
"Your age is " + year1 + " years " + mon1 + " months and "
+ dat1 + "days", Toast.LENGTH_LONG).show();
result.setText("AGE (DD/MM/YY) :" + age.getResult());
}
}



3. Sub class ( AgeCalculation.java)



public class AgeCalculation {
    private int startYear;
    private int startMonth;
    private int startDay;
    private int endYear;
    private int endMonth;
    private int endDay;
    private int resYear;
    private int resMonth;
    private int resDay;
    private Calendar start;
    private Calendar end;
    public String getCurrentDate()
{
 end=Calendar.getInstance();
 endYear=end.get(Calendar.YEAR);
 endMonth=end.get(Calendar.MONTH);
 endMonth++;
 endDay=end.get(Calendar.DAY_OF_MONTH);
 return endDay+":"+endMonth+":"+endYear;
}
public void setDateOfBirth(int sYear, int sMonth, int sDay)
    {
startYear=sYear;
startMonth=sMonth;
startMonth++;
startDay=sDay;
 
    }
public void calcualteYear()
{
resYear=endYear-startYear;
 
}
public void calcualteMonth()
{
if(endMonth>=startMonth)
{
resMonth= endMonth-startMonth;
}
else
{
resMonth=endMonth-startMonth;
resMonth=12+resMonth;
resYear--;
}
 
}
public void  calcualteDay()
{

if(endDay>=startDay)
{
resDay= endDay-startDay;
}
else
{
resDay=endDay-startDay;
resDay=30+resDay;
if(resMonth==0)
{
resMonth=11;
resYear--;
}
else
{
resMonth--;
}
 
}
}
 
public String getResult()
{
return resDay+":"+resMonth+":"+resYear;
}
public long getSeconde()
{
start=Calendar.getInstance();
start.set(Calendar.YEAR, startYear);
start.set(Calendar.MONTH, startMonth);
start.set(Calendar.DAY_OF_MONTH, startDay);
start.set(Calendar.HOUR, 12);
start.set(Calendar.MINUTE, 30);
start.set(Calendar.SECOND, 30);
start.set(Calendar.MILLISECOND, 30);
    long now=end.getTimeInMillis();
long old=start.getTimeInMillis();
long diff=old-now;
return diff/1000;
}
}


______________________________________________________

Source code for this application AgeCalculatorApp.zip

                                                    Happy Coding...

Comments

Popular posts from this blog

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ___________________________________________________________

Set Focus on Spinner when select Item on Vertical Scroll - Android Tutorial

We may face an issue on Spinner lies on long vertical scroll, (i.e.) when selected and item from dropdown the focus moves to top of scroll. To avoid this please follow this piece of code spinner.setFocusableInTouchMode( true ); spinner.setOnFocusChangeListener( new View.OnFocusChangeListener() {     @Override     public void onFocusChange(View v, boolean hasFocus) {         if (hasFocus) {             if (spinner.getWindowToken() != null ) {                 spinner.performClick();             }         }     } });   _______________________________________________________________________________ Happy Coding...