Android: use a datepicker and timepicker from within a Dialog

I am facing a problem I do not know how to solve... I have an activity, when I click on a particuliar item of the menu linked to this activity, a dialog is displayed and used to add an item. This item has a date and a time, but I do not manage to have a DatePicker and TimePicker within this dialog. I also try passing the activity to the dialog and use this one to display the datepicker., but that does not work. Before this, I handled the creation of such items within another Activity. In this case, it works fine. But I found the Dialog sexier... :-) Would you have any ideas ? Hope I am not too confused..... thanks a lot, Luc

I edit this post to share the code I have difficulties with.

I have a basic Dialog class that tried to use DatePicker and TimePicker. Basically, Eclipse complains that:

  • the showDialog is undefined for View.OnClickListener()
  • onCreateDialog method: The method onCreateDialog(int) of type EventCreateDialog must override or implement a supertype method
  • DatePickerDialog is undefined (as this is not an acitvity)

All this stuff works from within an Activity but I cannot have it working from a Dialog.

Thanks a lot, Luc

 package com.android.myapp;
import ...
public class TestDialog extends Dialog implements android.view.View.OnClickListener{
private TextView mDateDisplay;
private Button mPickDate;
private Button mPickTime;
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;
static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID = 1;

private Button mButton_ok;

private Button mButton_ko;

private ReadyListener readyListener;

private Context context;    

    public TestDialog(Context context, ReadyListener readyListener) {
        super(context);
        this.context = context;
        this.readyListener = readyListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_create);          

        mButton_ok = (Button)findViewById(R.id.button_ok);
        mButton_ko = (Button)findViewById(R.id.button_ko);

        // Add listeners
        mButton_ok.setOnClickListener(this);
        mButton_ko.setOnClickListener(this);

            mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
            mPickDate = (Button) findViewById(R.id.pickDate);
            mPickTime = (Button) findViewById(R.id.pickTime);
            // add a click listener to the button
            mPickDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) { showDialog(DATE_DIALOG_ID); }
            });
            mPickTime.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) { showDialog(TIME_DIALOG_ID); }
            });
            // get the current date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);
            updateDisplay();
    }   

        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
            }
            return null;
        }
        private void updateDisplay() {
            mDateDisplay.setText(
                new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" ")
                    .append(pad(mHour)).append(":")
                   .append(pad(mMinute)));
        }

        // the callback received when the user "sets" the date in the dialog
        private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
        };

        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mHour = hourOfDay;
                    mMinute = minute;
                    updateDisplay();
                }
        };

        private static String pad(int c) {
            if (c >= 10)
                return String.valueOf(c);
            else
                return "0" + String.valueOf(c);
        }

    public interface ReadyListener { 
        public void ready(MyObj myObj); 
    } 

     @Override
        public void onClick(View v) {
        if (v == mButton_ok) {
            // Do stuff....

        }


        if(v == mButton_ko){
            dismiss();
        }
     }
}

Answers


PickerViewSample.java

package com.sai.samples.views;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
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;
import android.widget.TimePicker;

public class PickerViewSample extends Activity {

    static final int DATE_DIALOG_ID = 1;
    static final int TIME_DIALOG_ID = 2;
    private TextView dateDisplay;
    private Button pickDate;
    private int year, month, day;
    private TextView timeDisplay;
    private Button pickTime;
    private int hours, min;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        dateDisplay = (TextView)findViewById(R.id.TextView01);
        pickDate = (Button)findViewById(R.id.Button01);

        pickDate.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }

        });

        final Calendar cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH);
        day = cal.get(Calendar.DAY_OF_MONTH);

        updateDate();

        timeDisplay = (TextView)findViewById(R.id.TextView02);
        pickTime = (Button)findViewById(R.id.Button02);

        pickTime.setOnClickListener( new OnClickListener () {

            @Override
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);

            }

        });

        hours = cal.get(Calendar.HOUR);
        min = cal.get(Calendar.MINUTE);

        updateTime();
    }

    private void updateTime() {
        timeDisplay.setText(new StringBuilder().append(hours).append(':')
                .append(min));

    }

    private void updateDate() {
        dateDisplay.setText(new StringBuilder().append(day).append('-')
                .append(month + 1).append('-').append(year));

    }

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

            @Override
            public void onDateSet(DatePicker view, int yr, int monthOfYear,
                    int dayOfMonth) {
                year = yr;
                month = monthOfYear;
                day = dayOfMonth;
                updateDate();
            }
    };

    private TimePickerDialog.OnTimeSetListener timeListener = 
        new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                hours = hourOfDay;
                min = minute;
                updateTime();
            }

    };
    protected Dialog onCreateDialog(int id){
        switch(id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, dateListener, year, month, day);
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this, timeListener, hours, min, false);
        }
        return null;

    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView android:text="@string/date_text" 
    android:id="@+id/TextView01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textSize="26px" 
    android:typeface="sans"></TextView>
<Button android:text="@string/date_button" 
    android:id="@+id/Button01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"></Button>

<TextView android:text="@string/time_text" 
    android:id="@+id/TextView02" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:textSize="26px" 
    android:typeface="sans"></TextView>
<Button android:text="@string/time_button" 
    android:id="@+id/Button02" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"></Button>
</LinearLayout>

datepickerlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
<DatePicker 
    android:id="@+id/DatePicker01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"></DatePicker>
</LinearLayout>

Here's what I have that works:

public class EditRecordDialog extends Dialog {
  protected Context _context;
  private   Record  _record;

  public EditRecordDialog( Context context,
                           Record  record ) {
    super( context );
    _context = context;
    _record  = record
    Button buttonDate;
    buttonDate.setText( _record.getRecordDate() ); // returns 'mm-dd-yy'

  } // EditRecordDialog


// showDatePickerDialog ++++++++++++++++++++++++++++++++++++++++++++++++++++++
private void showDatePickerDialog( View view ) {
  String dateString;
  int    year, month, day;

  dateString = buttonDate.getText().toString();
  month = Integer.valueOf( dateString.substring( 0, 2 ) ) - 1; // month is zero based
  day   = Integer.valueOf( dateString.substring( 3, 5 ) );
  year  = Integer.valueOf( "20" + dateString.substring( 6, 8 ) );

  DatePickerDialog dpd = new DatePickerDialog( _context, dateSetListener, year, month, day );
  dpd.show();

} // showDatePickerDialog ----------------------------------------------------


// OnDateSetListener +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
  @Override public void onDateSet( DatePicker view, int year, int month, int day ) {
    buttonDate.setText( ConfigObjectDAO.formatDate( (month+1) + "-" + day + "-" + year ) );
  } // onDateSet
}; // OnDateSetListener ------------------------------------------------------
}

this should work:

mPickDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) { context.showDialog(DATE_DIALOG_ID); }
            });

onCreateDialog can only be called from within an activity


Need Your Help

How to insert data using Core Data in IBAction

ios cocoa core-data

I want to create a button,ie "Done",when pressed, save all the data into Core Data,I am using the codes below

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.