I have a timepicker in my preference activity for setting the time when a notification should be displayed. The value is stored as a string, for example: "15:45". To understand the problem, I will further explain what happens next to the value:
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(context);
String hour = pref.getString("notification_time","");
// notification_time is my preference key
String Hora = hour;
int hours = Integer.parseInt(Hora.substring(0, 2));
int min = Integer.parseInt(Hora.substring(3, 5));
// as you can see, I parse the string, and then use the integers to set the time (see below)
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 00);
Now the problem is, My TimePicker stores the value differently, if the time is AM: for example, if you set the time to 07:45, it stores the time in the string as "7:45", not "07:45", and thus this line in the code fails:
int hours = Integer.parseInt(Hora.substring(0, 2));
(Throwing this error, not really necessary to understand the problem):
java.lang.NumberFormatException: Invalid int: "5:"
,because the position for "substring" isnt working anymore. (1 digit stored in the string instead of 2). Same goes for minutes, for example if I set the minutes to 08, my timepicker stores them as 8, and the same problem occurs again.
Now I have thought about two ways to solve this problem: Either I change the code in my settingsactivity and parse the string differently, or I change the way how I store the strings:
if (positiveResult) {
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);
if (callChangeListener(time)) {
persistString(time);
}
setSummary(getSummary());
}
(These are the lines of code responsible for saving the value as a string)
How should I solve the problem?
0 comments:
Post a Comment