Android Handler, DialogFragment and Time Picker Example

By Arvind Rai, June 10, 2015
This page will walk through Android Handler, DialogFragment and Time Picker Example with Message and Bundle. Handler is used to send and receive Message. DialogFragment creates fragment controlled by API that will prompt on top of activity window like alert box, date picker and time picker. We will create here a time picker dialog using TimePicker and TimePickerDialog. Bundle carries the data with Message. It provides put and get method for data. In our time picker dialog, after selecting time, it will be displayed on activity window with a text view.

Handler

android.os.Handler is used to send and process Message associated with a thread's message queue. The new instance of Handler is associated to the thread which has created it and its message queue. Handler is used to schedule messages at any future point and it enqueues action to be performed on any different threads. In case of creating any Dialog, we can send the message to it and can get return the messages sent by Dialog with the help of Handler. Find some methods of Handler.

handleMessage(Message msg): Receives the messages. The subclass must implement this method.
dispatchMessage(Message msg) : Used for system message.
obtainMessage() : Returns Message.
post(Runnable r) : Adds Runnable instance to message queue.
sendMessage(Message msg) : Pushes the message at the end of message queue.

In our example we are creating a time picker dialog. Using Handler we pass the current time to time picker dialog and get return the set time by dialog. To achieve it, we do code as below. Create the instance of Handler overriding the handleMessage(). Create a class extending Handler and override its handleMessage().
class MyHandler extends Handler {
    @Override
    public void handleMessage (Message msg){
    	Bundle bundle = msg.getData();
    	timeHour = bundle.getInt(MyConstants.HOUR);
    	timeMinute = bundle.getInt(MyConstants.MINUTE);
    	textView.setText(timeHour + ":" + timeMinute);
    }
} 
By Message instance we get Bundle instance and can get all the information added to it. To send message back by any Dialog, we use
Message msg = new Message();
msg.setData(b);
Handler.sendMessage(msg);  
We will see the full example in our post for Handler .

DialogFragment

android.support.v4.app.DialogFragment is a fragment which opens a dialog on top of activity window. The control of dialog is done by API. To use it we have to write a class extending DialogFragment and override a method onCreateDialog(Bundle). In this way, we create an entirely custom dialog. Dialogs are often autonomous window which decides its input and disappear by its own time receiving any button click etc. Find some methods of it.

onCreate (Bundle savedInstanceState) : It takes part in initial creation of fragment.
onCreateDialog(Bundle savedInstanceState) : It returns Dialog and helps to create custom dialog.
onDestroyView() : It is called when dialog is removed.
onStart() : It is called when dialog is viewable to user.
onStop() : It is called when fragment is stopping.

In our example we are creating time picker dialog using DialogFragment.

TimePicker and TimePickerDialog

android.widget.TimePicker is a view in which we can select hour and minute of the day using 24 hour view or 12 hour view with AM and PM. We can select hour and minute using vertical spinner. We can also enter data using keyboard. android.app.TimePickerDialog is displays a dialog for TimePicker. TimePickerDialog has two public constructors. We create the instance of it by passing context, hour, minute and Boolean value for 24 hour view.

Message

android.os.Message is used to define message that is sent to Handler. Find some method details.

setData(Bundle data) : Sets a bundle.
getData(): Returns a bundle.
getTarget() : Returns the target handler that will receive message.
copyFrom(Message ob) : Copy the calling message into the argument message i.e ob.

Bundle

android.os.Bundle extends android.os.BaseBundle and is used to map String values to Parcelable types. We put the values as int, String etc. It provides methods like putInt(), putChar() etc and to fetch values it has methods like getInt(), getChar() etc.

Complete Example

Now find the complete example. Here we will create a time picker dialog using which we can select time. The selected time will be displayed using text view.

Software Used in Example

In our example we are using software and tools as follows.
1. Java 7
2. Android 4.4W
3. Eclipse

FragmentActivity and DialogFragment Implementation

MainActivity.java
package com.concretepage.android;
import java.util.Calendar;
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.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.concretepage.R;
public class MainActivity extends FragmentActivity{
	private static int timeHour = Calendar.getInstance().get(Calendar.HOUR);
	private static int timeMinute = Calendar.getInstance().get(Calendar.MINUTE);
	TextView textView;
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.mylayout);
		textView = (TextView)findViewById(R.id.msg);
		textView.setText(timeHour + ":" + timeMinute);
                OnClickListener listener = new OnClickListener() {
			public void onClick(View view) {
				Bundle bundle = new Bundle();
				bundle.putInt(MyConstants.HOUR, timeHour);
				bundle.putInt(MyConstants.MINUTE, timeMinute);
				MyDialogFragment fragment = new MyDialogFragment(new MyHandler());
				fragment.setArguments(bundle);
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                transaction.add(fragment, MyConstants.TIME_PICKER);
                                transaction.commit();
			}
               };
               Button btn = (Button)findViewById(R.id.button);
               btn.setOnClickListener(listener);
        }
        class MyHandler extends Handler {
    	       @Override
    	       public void handleMessage (Message msg){
    		   Bundle bundle = msg.getData();
    		   timeHour = bundle.getInt(MyConstants.HOUR);
    		   timeMinute = bundle.getInt(MyConstants.MINUTE);
    		   textView.setText(timeHour + ":" + timeMinute);
    	       }
       }
}  

MyDialogFragment.java
package com.concretepage.android;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.widget.TimePicker;
public class MyDialogFragment extends DialogFragment {
	private int timeHour;
	private int timeMinute;
	private Handler handler;
	public MyDialogFragment(Handler handler){
		this.handler = handler;
	}
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        timeHour = bundle.getInt(MyConstants.HOUR);
        timeMinute = bundle.getInt(MyConstants.MINUTE);
		TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				timeHour = hourOfDay;
				timeMinute = minute;
				Bundle b = new Bundle();
				b.putInt(MyConstants.HOUR, timeHour);
				b.putInt(MyConstants.MINUTE, timeMinute);
				Message msg = new Message();
				msg.setData(b);
				handler.sendMessage(msg);
			}
		};
	        return new TimePickerDialog(getActivity(), listener, timeHour, timeMinute, false);
	}
} 

MyConstants.java
package com.concretepage.android;
public abstract class MyConstants {
	public static final String HOUR = "time_hour";
	public static final String MINUTE = "time_minute";
	public static final String TIME_PICKER = "time_picker";
} 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11" />
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.concretepage.android.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Layout XML


mylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="#FF0000"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_label"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
	android:layout_gravity="center"
	android:textColor="#b0b0ff"
	android:textSize="80sp"
	android:id="@+id/msg"/>
</LinearLayout> 

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Concrete Page</string>
    <string name="btn_label"> Change Time </string>
</resources> 

Output

Find the output.
Android  Handler, DialogFragment  and Time Picker Example with Message and Bundle

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us