user3182266 user3182266 - 6 months ago 36
Android Question

Timepicker displaying time incorrectly

I am having a weird problem. When I try to select the time using

Time-picker
I get a weird result.

For example if I set the time to
11:04
the output is
11:4
???

Also if I set the time to
12:30
the output is
12:3
???

//Time Picker Dialog
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case dialog_id:
return new TimePickerDialog(this, mTimeSetListener, hour, minute, false);
}
return null;
}

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

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int hour_minute)
{
hour = hourOfDay;
minute = hour_minute;

if (hourOfDay > 12)
{
hour = hourOfDay - 12;
amORpm = "PM";
}
else
{
hour = hourOfDay;
amORpm = "AM";
}

textBox.setText(hour + " : " + minute + " " + amORpm);

Toast.makeText(getBaseContext(), "Arrival time changed to: " + hour +":" + minute , Toast.LENGTH_LONG).show();

}
};

Answer

Use this Class

public class TimeListener implements OnClickListener, OnTimeSetListener {

    private int hour;
    private int minute;
    private Activity activity;
    private View touchedView;

    public TimeListener(Activity activity) {
        this.activity = activity;
        final Calendar c = Calendar.getInstance();
        this.hour = c.get(Calendar.HOUR_OF_DAY);
        this.minute = c.get(Calendar.MINUTE);
    }

    public int getHour() {
        return hour;
    }

    public int getMinute() {
        return minute;
    }


    @Override
    public void onClick(View v) {
        touchedView = v;

        new TimePickerDialog(activity,
                this, this.getHour(), this.getMinute(), false).show();
    }

    private void updateDisplay() {
        ((TextView) touchedView).setText(
            new StringBuilder()
                    .append(pad(hour)).append(":")
                    .append(pad(minute)));
    }

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

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        this.hour = hourOfDay;
        this.minute = minute;
        updateDisplay();
    }
}

and use below code Inside your Activity Class...

private TimeListener timeListener = new TimeListener(this);
view.setOnClicklistner(timeListener);

Thank you...