Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimePicker getHours(), getMinutes in API 15

I'm making a simple Alarm Clock app, to study BroadcastReceivers , the problem is getHours() and getMinutes() are only available for API 23.

  • Is there any alternative way of achieving this?
  • If so? Will it possible solution be applicable to higher API like 24?

Here's my sample code: AlarmActivity.java

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm);

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    setWidgets();

    Intent intent = new Intent(this.context, AlarmReceivers.class);

}

public void setWidgets(){
    timePicker = (TimePicker) findViewById(R.id.timePicker);
    //Calendar calendar = Calendar.getInstance();

    buttonSetAlarm = (Button) findViewById(R.id.buttonSetAlarm);
    buttonSetAlarm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int getHour = timePicker.getHour();
            int getMinute = timePicker.getMinute();

            calendar.set(Calendar.HOUR_OF_DAY,timePicker.getHour());
            calendar.set(java.util.Calendar.MINUTE, timePicker.getMinute());

            if (getHour > 12){
                int twelve = getHour - 12;
            }

            if (getMinute < 10){

            }

            setText("On");

        }
    });

I'm stuck with the getHour() and getMinute().

like image 788
RoCk RoCk Avatar asked Dec 04 '22 00:12

RoCk RoCk


2 Answers

You can use the get() Methode from the Calendar class.

calendar.get(Calendar.HOUR);
calendar.get(Calendar.MINUTE);
like image 32
Lasse Sb Avatar answered Jan 07 '23 11:01

Lasse Sb


As getHour() and getMinute() are for API 23 and above, if your application targets lower APIs you need to add support for them.

You can do this by adding the following:

if(Build.VERSION.SDK_INT < 23){
    int getHour = timePicker.getCurrentHour();
    int getMinute = timePicker.getCurrentMinute();

    calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
    calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
} else{
    int getHour = timePicker.getHour();
    int getMinute = timePicker.getMinute();

    calendar.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
    calendar.set(Calendar.MINUTE, timePicker.getMinute());
}

Both getCurrentHour() and getCurrentMinute() are deprecated but still work on lower APIs.

like image 71
Goateed Dev Avatar answered Jan 07 '23 11:01

Goateed Dev