2

I have these code and work well to show time from timePicker. the code use getCurrentHour and getCurrentMinute.

public void setTime(View view) {
    int hour = timePicker1.getCurrentHour();
    int min = timePicker1.getCurrentMinute();
    showTime(hour, min);
}

public void showTime(int hour, int min) {
    if (hour == 0) {
        hour += 12;
        format = "AM";
    }
    else if (hour == 12) {
        format = "PM";
    } else if (hour > 12) {
        hour -= 12;
        format = "PM";
    } else {
        format = "AM";
    }
    time.setText(new StringBuilder().append(hour).append(" : ").append(min)
            .append(" ").append(format));
}

The android Studio tell me to use new getHour() and getMinute() instead.

when I use them in the code above the app stop and crash. why and how to use them correctly.

This is the error in logcat: Caused by: java.lang.NoSuchMethodError: No virtual method getHour()I in class Landroid/widget/TimePicker; or its super classes (declaration of 'android.widget.TimePicker' appears in /system/framework/framework.jar:classes2.dex)

Khorshid
  • 303
  • 4
  • 16

3 Answers3

12

You can check SDK version using android.os.Build.VERSION.SDK_INT:

int hour = 0;
int min = 0;

int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion > android.os.Build.VERSION_CODES.LOLLIPOP_MR1){
    hour = timePicker1.getHour();
    min = timePicker1.getMinute();
} else {
    hour = timePicker1.getCurrentHour();
    min = timePicker1.getCurrentMinute();
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
0

Ok, it works well with new time functions getMinute() and getHour() in emulator, So the problem probably cause because of API used. These tow functions require API 23.

Khorshid
  • 303
  • 4
  • 16
0

This answer is all you need don't follow other guides. Do the check and then just use timePicker.getCurrentHour and timePicker.getCurrentHour this is for below API 23. For 23 and above use timePicker.getHour and timePicker.getMinute for minutes.

abpatil
  • 916
  • 16
  • 20