RED_
RED_

Reputation: 3007

Create an alarm from a string?

I have an app that generates random times, then stores those times in separate TextViews. Is it possible for me to set alarms up for these times using AlarmManager? I've seen other bits of code on this site and they all show the alarm time hardcoded. Stuff like this for example:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Obviously I can't do that because my times are random. So my app will generate a few times and next to each I add a button that reads "Set alarm". The user can also pick their own time, but that's in a String as well.

How do I get the String/TextView to be used as the time to set the alarm? If it helps the times appear in a 24Hr format.

Appreciate any help!

EDIT: Here is part of what I have now.

DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
userEnterTime = (userTime.toString(formatter));


Intent a = new Intent(this, Alarm.class);
a.putExtra("usertime", userEnterTime);  
startActivity(a);

Activity 'a' then assigns it to a TextView.

Upvotes: 0

Views: 265

Answers (1)

Raghav Sood
Raghav Sood

Reputation: 82563

You can simply parse the String and split it at the colon to get the hours and minutes, then use Integer.parseInt() to convert them to ints, and pass them to the Calendar.set() method.

String yourTime = "hh:mm"; //replace with time

String arr = yourTime.split(":");

int hours = Integer.parseInt(arr[0]);
int mins = Integer.parseInt(arr[1]);

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hours);
cal.set(Calendar.MINUTE, mins);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

You should add a try-catch for NumberFormatException while you're about it.

Upvotes: 1

Related Questions