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

Zoom Image - Android Tutorial

Here we are going to see how to zoom an image in Imageview Will see it through a sample 1. Create xml with an ImageView <? xml version="1.0" encoding="utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout       xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity" >     < LinearLayout         android:layout_width="200dp"         android:layout_height="200dp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintLeft_toLeftOf="parent"         app:layout_constraintRight_toRightOf="parent"    ...

Multi language support

This post will help you yo learn how to make Multi language supported app in android. Why Multi language? In order to targeting global audience, it will be beneficial if you make your app localized. While localizing, you should think about text, audio, currency, numbers and graphics depending upon the region or country. But in this tutorial language only covered. Note: Whenever you are making any android application, Always declare text you want to use in your application in strings.xml only. <string name="hello">Hello World!</string> How String Localization Works? By default android considers English as primary language and loads the string resources from res >> values >> strings.xml . When you want to make Multilanguage supported app, you need to create a values folder by appending a Hyphen (-) and the ISO language code. For example for Hindi, values-hi named folder should be created and keep a strings.xml file in it wit...

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" /> ______________________________________...