Displaying DatePickerDialog using DialogFragment in Android with backward compatibilty support library

August 16, 2012
By

In this article we will create an Android application which demonstrate how to display a datepicker widget using dialog fragment. Since DialogFragment is introduced beginning with Android 3.0 ( API level 11 ) , we will make use Android support library to work this application in Android 1.6 ( API level 4 ) and its higher versions.

In this application, the set date is sent from DatePickerDialog to MainActivity using Handler object.

This application is developed using Eclipse IDE ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3)


1. Create new Android Application Project namely “DatePickerDialogDemo”

New Android Application Project

Figure 1 : New Android Application Project


2. Design Application launcher Icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Add Android support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project ( “DatePickerDialogDemo”)
  • Then from popup window, Click “Android Tools -> Add Support Library “

6. Update the file res/values/strings.xml


<resources>
    <string name="app_name">DatePickerDialogDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">DatePickerDialog Demo</string>
    <string name="str_btn_label">Set Date !!!</string>
</resources>


7. Update the layout file res/layout/activity_main.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" >

    <Button
        android:id="@+id/btnSet"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_label"
    />

</RelativeLayout>


8. Create a fragment class DatePickerDialogFragment in the file src/in/wptrafficanalyzer/datepickerdialogdemo/DatePickerDialogFragment.java


package in.wptrafficanalyzer.datepickerdialogdemo;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

public class DatePickerDialogFragment extends DialogFragment{
    Handler mHandler ;
    int mDay;
    int mMonth;
    int mYear;

    public DatePickerDialogFragment(Handler h){
        /** Getting the reference to the message handler instantiated in MainActivity class */
        mHandler = h;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){

        /** Creating a bundle object to pass currently set date to the fragment */
        Bundle b = getArguments();

        /** Getting the day of month from bundle */
        mDay = b.getInt("set_day");

        /** Getting the month of year from bundle */
        mMonth = b.getInt("set_month");

        /** Getting the year from bundle */
        mYear = b.getInt("set_year");

        /** DatePickerDialog's "Set" click listener */
        DatePickerDialog.OnDateSetListener listener  = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                mDay = dayOfMonth;
                mMonth = monthOfYear;
                mYear = year;

                /** Creating a bundle object to pass currently set date to the fragment */
                Bundle b = new Bundle();

                /** Adding currently set day to bundle object */
                b.putInt("set_day", mDay);

                /** Adding currently set month to bundle object */
                b.putInt("set_month", mMonth);

                /** Adding currently set year to bundle object */
                b.putInt("set_year", mYear);

                /** Adding Current date in a string to bundle object */
                b.putString("set_date", "Set Date : " + Integer.toString(mDay) + " / " + Integer.toString(mMonth+1) + " / " + Integer.toString(mYear));

                /** Creating an instance of Message */
                Message m = new Message();

                /** Setting bundle object on the message object m */
                m.setData(b);

                /** Message m is sending using the message handler instantiated in MainActivity class */
                mHandler.sendMessage(m);
            }
        };

        /** Opening the DatePickerDialog window */
        return new DatePickerDialog(getActivity(), listener, mYear, mMonth, mDay);
    }
}


9. Update the MainActivity class in the file src/in/wptrafficanalyzer/datepickerdialogdemo/MainActivity.java


package in.wptrafficanalyzer.datepickerdialogdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
    int mDay = 15;
    int mMonth = 7; // August, month starts from 0
    int mYear= 2012;

    /** This handles the message send from DatePickerDialogFragment on setting date */
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message m){
            /** Creating a bundle object to pass currently set date to the fragment */
            Bundle b = m.getData();

            /** Getting the day of month from bundle */
            mDay = b.getInt("set_day");

            /** Getting the month of year from bundle */
            mMonth = b.getInt("set_month");

            /** Getting the year from bundle */
            mYear = b.getInt("set_year");

            /** Displaying a short time message containing date set by Date picker dialog fragment */
            Toast.makeText(getBaseContext(), b.getString("set_date"), Toast.LENGTH_SHORT).show();
        }
    };

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

        /** Click Event Handler for button */
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {

                /** Creating a bundle object to pass currently set date to the fragment */
                Bundle b = new Bundle();

                /** Adding currently set day to bundle object */
                b.putInt("set_day", mDay);

                /** Adding currently set month to bundle object */
                b.putInt("set_month", mMonth);

                /** Adding currently set year to bundle object */
                b.putInt("set_year", mYear);

                /** Instantiating DatePickerDialogFragment */
                DatePickerDialogFragment datePicker = new DatePickerDialogFragment(mHandler);

                /** Setting the bundle object on datepicker fragment */
                datePicker.setArguments(b);

                /** Getting fragment manger for this activity */
                FragmentManager fm = getSupportFragmentManager();

                /** Starting a fragment transaction */
                FragmentTransaction ft = fm.beginTransaction();

                /** Adding the fragment object to the fragment transaction */
                ft.add(datePicker, "date_picker");

                /** Opening the DatePicker fragment */
                ft.commit();
            }
        };

        /** Getting an instance of Set Date button */
        Button btnSet = (Button)findViewById(R.id.btnSet);

        /** Setting click event listener for the button */
        btnSet.setOnClickListener(listener);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


10. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.datepickerdialogdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter
                android:label="@string/app_name"
            >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


11. Screenshot of the application in execution

DatePickerDialog window in execution

Figure 5 : DatePickerDialog window in execution


12. Download


13. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , , , ,

4 Responses to Displaying DatePickerDialog using DialogFragment in Android with backward compatibilty support library

  1. Tofeeq on October 20, 2012 at 3:16 pm

    Nice article ..but i think you should remove first three step in every project. If you taught some one about Dialog Fragment that means one is not newbie in android.These first three screen shot waste space and force user to scroll with any reason. Rather than this i am fan of your way of writing

    • george on October 21, 2012 at 9:48 am

      Thanks for your suggestion.
      The first screenshot is needed because it depicts the minimum required sdk and build sdk. On the other hand, the rest of the screenshots are needed for its continuity.

  2. André Cruz on November 2, 2012 at 4:21 am

    One note:
    mHandler handler class should be static or leaks might occur.

    Info from lint.

  3. Hozi Suratwala on March 28, 2014 at 8:02 pm

    Hi great tutorial, thanks so much. I was struggling with the date picker for a long time.

    I have a question.
    I want to add to be able to display the date on my activity like so

    @Override
    public void onDateSet(DatePicker view, int year, int month, int day){
    ((EditText)findViewById(R.Id.dateDisplay)).setText(“Date: ” + month + “/” + day + “/” + year);
    }

    I am not sure how to incorporate this in to my activity.
    Any help would be great.

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner