Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to get the time from a TimePicker when it is typed in

I've got a DialogPreference which implements a simple TimePicker.OnTimeChangedListener (see below). Setting the time by clicking the +/- buttons works great. But I don't know how to save the state of the timepicker when the user typed in the time directly into the textfield. It could be sufficient to access to the current textfield value, so I'd be able to persist it in onDialogClosed. But timePicker.getCurrentHour() won't do it. Please help...

public class TimePreference extends DialogPreference implements
        TimePicker.OnTimeChangedListener {
// ...
@Override
public void onTimeChanged(TimePicker view, int hours, int minutes) {
    selectedHours = hours;
    selectedMinutes = minutes;
}

@Override
public void onDialogClosed(boolean positiveResult) {
    if(positiveResult) {
        String timeString = selectedHours + ":" + selectedMinutes;
        if(isPersistent()) {
            persistString(timeString);
        }
    }
}
// ...
}
like image 817
cody Avatar asked Oct 21 '10 23:10

cody


1 Answers

I hadn't noticed this problem until i stumbled upon this question. There is a simple solution: When the user is done changing the date and time in my app, i simply call finish() and in the onPause() or onStop() or onDestroy() I do this:

// force the timepicker to loose focus and the typed value is available !
timePicker.clearFocus();
// re-read the values, in my case i put them in a Time object.
time.hour   = timePicker.getCurrentHour();
time.minute = timePicker.getCurrentMinute();

After this i store the time.toMillis(false) value in the appropriate column of my table.

I don't know if the timepicker is still accessible in your onDialogClosed(boolean positiveResult). If not, find another callback to use when it still is.

Hope this helps.

like image 165
Larphoid Avatar answered Oct 09 '22 12:10

Larphoid