DatePicker

Android Date Picker Example

Android it’s very easy to set the date using the android.widget.DatePicker component. In this tutorial we are going to see how the user can change the day, the month and the year using the android.app.DatePickerDialog which is an easy to use dialog box.
 
 
 
 
 
 
 
 
 
For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package Name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

2. Adding resources

Use the Package Explorer in Eclipse to navigate to res/values/strings.xml

When you open the strings.xml file, Eclipse will display the graphical Resources View editor :

That’s a nice and easy tool you can use to add several resources to your application like strings, integers, color values etc. But we are going to use the traditional way and that is editing the strings.xml file by hand. In the bottom of the screen, press the string.xml tab and paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">DatePickerExample</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="cur_date">Current Date (M-D-YYYY): </string>
    <string name="ch_label">Change Date</string>

</resources>

So, we’ve just created some string resources that we can use in many ways and in many places in our app.

3. Creating the Date Picker

Open res/layout/main.xml file :

And paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ch_label" />

    <TextView
        android:id="@+id/date_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cur_date"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/text_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

4. Change the default AppTheme

This step is optional, but in my system with the default theme, the Date Picker didn’t work properly. So, if the Date Picker doesn’t seem to work as it was supposed to, go to res/values/styles.xml file:

And paste the following code:

<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="android:Theme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>

5. Coding

Go to the java file that contains the code of the activity you’ve just created and paste the following code:

package com.javacodegeeks.android.datepickerexample;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView text_date;
	private DatePicker date_picker;
	private Button button;

	private int year;
	private int month;
	private int day;

	static final int DATE_DIALOG_ID = 100;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		setCurrentDate();
		addButtonListener();

	}

	// display current date both on the text view and the Date Picker when the application starts.
	public void setCurrentDate() {

		text_date = (TextView) findViewById(R.id.text_date);
		date_picker = (DatePicker) findViewById(R.id.date_picker);

		final Calendar calendar = Calendar.getInstance();

		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DAY_OF_MONTH);

		// set current date into textview
		text_date.setText(new StringBuilder()
			// Month is 0 based, so you have to add 1
			.append(month + 1).append("-")
			.append(day).append("-")
			.append(year).append(" "));

		// set current date into Date Picker
		date_picker.init(year, month, day, null);

	}

	public void addButtonListener() {

		button = (Button) findViewById(R.id.button);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				showDialog(DATE_DIALOG_ID);

			}

		});

	}
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DATE_DIALOG_ID:
		   // set date picker as current date
		   return new DatePickerDialog(this, datePickerListener, year, month,day);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// set selected date into Text View
			text_date.setText(new StringBuilder().append(month + 1)
			   .append("-").append(day).append("-").append(year).append(" "));

			// set selected date into Date Picker
			date_picker.init(year, month, day, null);

		}
	};

}

When MainActivity is launched, the setCurrentDate() method finds out the current date using java.util.Calendar and sets up the values in the TextView and in the Date Picker.

As you can see, in the above code we add a ClickListener to the button. When the button is clicked, the OnClick method is called. The OnClick method calls showDialog(). When showDialog() is called, automatically the onCreateDialog method is called which creates and returns a new DatePickerDialog. Now, the DatePickerDialog takes a datePickerListener as an argument. So, when the users changes the date on the DatePickerDialog, the onDateSet method is called which updates the date both on the TextView and on the Date Picker.

6. Run the application

This is the main screen of our Application. As you will notice the current date is displayed :

Now if we click “Change Date” the DatePickerDialog  will show up:

And when we click done, the onDateSet method will be called, so both the TextView and the Date Picker will have the Date the user selected.

Download Eclipse Project

This was an Android Date Picker Example. Download the Eclipse Project of this tutorial: AndroidDatePickerExample.zip

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
niles
6 years ago

Nice post , Thanks

Back to top button