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

我试图从selected values获取hourminutetimePicker,然后从用户的设备获取当前的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

在Api 23

仅供参考。

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");

}

45码