获取分钟和小时时,TimePicker 使应用程序崩溃

TimePicker crashes app when getting the minute and hour

我正在尝试从 timePicker 中获取 hourselected valuesminute,然后从用户的 system time 中获取当前的 system time设备。之后我需要 subtract time selected - time.now 然后向用户显示闹钟响起之前的剩余时间。

但是应用程序崩溃了,我找不到解决方法。

@TargetApi(Build.VERSION_CODES.M)
public void onClickAlarmOn(View v) {

    final Calendar c = Calendar.getInstance();
    TimePicker alarm_time_picker = (TimePicker) findViewById(R.id.timePicker);
    int hour = alarm_time_picker.getHour(); //get selected hour
    int minute = alarm_time_picker.getMinute(); //get selected minute

    int hour_now = c.get(Calendar.HOUR); //get system's hour
    int minute_now = c.get(Calendar.MINUTE); //get system's minute

    int hour_result = hour - hour_now; //subtract the time selected by time.now of system
    int minute_result = minute - minute_now;

    String hour_result_string = String.valueOf(hour_result); //convert to string to display
    String minute_result_string = String.valueOf(minute_result);

    setToast_result("Alarm set to " + hour_result_string + " hours " + minute_result_string + " minutes");
}

谢谢!

首先我 运行 您在 Lollipop Device 中的代码,但与您的输出相同 App is crash.

然后我阅读了文档http://developer.android.com/reference/android/widget/TimePicker.html

在Api23

仅供参考。

getCurrentHour()

此方法已在 API 级别 23 中弃用。使用 getHour()

getCurrentMinute()

此方法已在 API 级别 23 中弃用。使用 getMinute()

现在我更换了设备 运行 在 MarshMallow 它工作正常。

这样使用代码:

final Calendar c = Calendar.getInstance();
    TimePicker alarm_time_picker = (TimePicker) findViewById(R.id.timePicker);



alarm_time_picker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    
    int hour = alarm_time_picker.getHour(); //get selected hour
    int minute = alarm_time_picker.getMinute();


int hour_now = c.get(Calendar.HOUR); //get system's hour
int minute_now = c.get(Calendar.MINUTE); //get system's minute

int hour_result = hour - hour_now; //subtract the time selected by time.now of system
int minute_result = minute - minute_now;

String hour_result_string = String.valueOf(hour_result); //convert to string to display
String minute_result_string = String.valueOf(minute_result);

setToast_result("Alarm set to " + hour_result_string + " hours " + minute_result_string + " minutes");

}