Android Date Picker

0
797

Android DatePicker UI control helps the user to select a date from a custom user interface. This date generally consists of a year, a month, and the day of the month. To adopt this functionality in an application, a developer needs to use the DatePicker and the DatePickerDialog components.

Also Read: Android Progress Bar

Various Methods Controlling Android DatePicker Component
Here, we will be using DatePickerDialog class which allows a developer to use Date Picker in an Android application. The DatePickerDialog can be defined as a simple dialog box which contains the DatePicker. If you want to access the DatePickerDialog in your application then use the following syntax where you need to enter the DatePickerDialog id as the argument passed to the method.

showDialog(dialog_id);

For example, if the DatePickerDialog id is 666 then after using this data in the syntax mentioned above, you will get the following method: showDialog(666);

Whenever the showDialog(dialog_id) method is called during the runtime of the application, the onCreateDialog(int id) method is called automatically. So, make sure that you override this method during the development phase of the Android application. For your better understanding, we have included the overriden method below.

@Override
protected Dialog onCreateDialog(int id)
{
   // TODO Auto-generated method stub
   if (id == 999)
   {
      return new DatePickerDialog(this, myDateListener, year, month, day);
   }
   return null;
}

The last step of the method clearly shows that you need to register the DatePickerDialog listener and ensure that you override the used onDateSet() method too. In the below provided section of code, you can easily see that this onDateSet() method accepts three arguments which are a year, a month, and the day of the month.

private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener()
{
   @Override
   public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3)
   {
      // arg1 = year
      // arg2 = month
      // arg3 = day
   }
};

The following tables contain a list of the major methods supported by the DatePicker control. Other than the DatePicker attributes itself, these methods also accept the DatePicker object which has been passed to them.

S. No. Method Description
1 getDayOfMonth() * This get method returns the selected day of the month.
2 getMonth() * This get method returns the selected month.
3 getYear() * This get method returns the selected year.
4 getFirstDayOfWeek() * This get method returns the selected first day of the week.
5 getCalendarView() * This get method returns the calendar view to the application.
6 setMaxDate(long maxDate) * This method acts as a Number Picker (set in milliseconds) which sets a maximal date up to which a user can input the date.
7 setMinDate(long minDate) * This method acts as a Number Picker (set in milliseconds) which sets a minimal date starting from which a user can input the date.
* When this method is used with getDefault() method, the default date and time would be January 1, 1970, 00:00:00.
8 setSpinnersShown(boolean shown) * This method indicates the presence of the spinner in the application.
9 updateDate(int year, int month, int dayOfMonth) * This method is used to update the current date indicating a year, a month, and the day of the month.

The following example will help you to understand the use of the DatePickerDialog class in your application. The application will be containing the basic Date Picker that permits a user to set a date with the help of DatePicker widget. Here, you will get a step-to-step guide on how to do it exactly.

Step 1: Open the Android Studio IDE and create an application here. Store this application under the com.example.datepicker package after naming it as DatePicker.

Step 2: Now, follow the src/com.example.datepicker/ path to find the MainActivity.java file. You need to update this file accordingly as shown in the following code.

package com.example.datepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast; 

public class MainActivity extends Activity
{
   private DatePicker datePicker;
   private Calendar calendar;
   private TextView dateView;
   private int year, month, day; 

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);      
      dateView = (TextView) findViewById(R.id.textView3);
      calendar = Calendar.getInstance();
      year = calendar.get(Calendar.YEAR);      
      month = calendar.get(Calendar.MONTH);
      day = calendar.get(Calendar.DAY_OF_MONTH);
      showDate(year, month+1, day);
   } 

   @SuppressWarnings(“deprecation”)
   public void setDate(View view)
   {
      showDialog(999);
      Toast.makeText(getApplicationContext(), “ca”,
         Toast.LENGTH_SHORT)
      .show();
   } 

   @Override
   protected Dialog onCreateDialog(int id)
   {
      // TODO Auto-generated method stub
      if (id == 999)
      {
         return new DatePickerDialog(this,
            myDateListener, year, month, day);
      }
      return null;
   } 

   private DatePickerDialog.OnDateSetListener myDateListener = new
      DatePickerDialog.OnDateSetListener()
   {
      @Override
      public void onDateSet(DatePicker arg0,
         int arg1, int arg2, int arg3)
         {
         // TODO Auto-generated method stub
         // arg1 = year
         // arg2 = month
         // arg3 = day
         showDate(arg1, arg2+1, arg3);
      }
   };

   private void showDate(int year, int month, int day)
   {
      dateView.setText(new StringBuilder().append(day).append(“/”)
      .append(month).append(“/”).append(year));
   }
} 

Step 3: You also need to modify the activity_main.xml file. Trace the res/layout/ directory to get to this file. The updated content of this file will be carrying the code to add the required XML components.

<?xml version=”1.0″ encoding=”utf-8″?>
<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:paddingBottom=”@dimen/activity_vertical_margin”
   android:paddingLeft=”@dimen/activity_horizontal_margin”
   android:paddingRight=”@dimen/activity_horizontal_margin”
   android:paddingTop=”@dimen/activity_vertical_margin”
   tools:context=”.MainActivity” > 

   <Button
      android:id=”@+id/button1″
      android:layout_width=”wrap_content”
      android:layout_height=”wrap_content”
      android:layout_alignParentTop=”true”
      android:layout_centerHorizontal=”true”
      android:layout_marginTop=”70dp”
      android:onClick=”setDate”
      android:text=”@string/date_button_set” /> 

   <TextView
      android:id=”@+id/textView1″
      android:layout_width=”wrap_content”
      android:layout_height=”wrap_content”
      android:layout_alignParentTop=”true”
      android:layout_centerHorizontal=”true”
      android:layout_marginTop=”24dp”
      android:text=”@string/date_label_set”
      android:textAppearance=”?android:attr/textAppearanceMedium” /> 

   <TextView
      android:id=”@+id/textView2″
      android:layout_width=”wrap_content”
      android:layout_height=”wrap_content”
      android:layout_below=”@+id/button1″
      android:layout_marginTop=”66dp”
      android:layout_toLeftOf=”@+id/button1″
      android:text=”@string/date_view_set”
      android:textAppearance=”?android:attr/textAppearanceMedium” /> 

   <TextView
      android:id=”@+id/textView3″
      android:layout_width=”wrap_content”
      android:layout_height=”wrap_content”
      android:layout_alignRight=”@+id/button1″
      android:layout_below=”@+id/textView2″
      android:layout_marginTop=”72dp”
      android:text=”@string/date_selected”
      android:textAppearance=”?android:attr/textAppearanceMedium” />
</RelativeLayout>

Step 4: Even the strings.xml file needs some modification. Once you start following the res/values/ path, you will find this file there.

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
   <string name=”app_name”>DatePicker</string>
   <string name=”action_settings”>Settings</string>
   <string name=”hello_world”>Hello world!</string>
   <string name=”date_label_set”>Press the button to set the date</string>
   <string name=”date_button_set”>Set Date</string>
   <string name=”date_view_set”>The Date is: </string>
   <string name=”date_selected”></string>
</resources>

Step 5: The only step left is to run this newly created application, which is DatePicker. We are assuming that you have already created the AVD during the environment setup. To run this application, you need to open one of the project’s activity files and hit the Run button. The Android Studio IDE then install this app on your AVD and when the process finishes successfully, you will be displayed with the final output on the as shown in the following screenshot.

 

In the above provided screenshot, you can easily see that the date is already set but you do have an option to SET DATE (button control). Now, you need to change this date which has been made possible only with the help of DatePickerDialog. Just click on the “SET DATE” button and a calendar (Date Picker Dialog box) will appear on the screen. After this, select a date with which you want to update your application.

The date will be updated once you click on the OK button. Even the dialog box will disappear after that. Now, you can see the newly set date on the screen now. The screenshot is provided below.