【发布时间】:2015-04-20 03:33:35
【问题描述】:
我的偏好活动中有一个时间选择器,用于设置显示通知的时间。该值存储为字符串,例如:“15:45”。为了理解这个问题,我将进一步解释该值旁边会发生什么:
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);
现在的问题是,My TimePicker 存储值的方式不同,如果时间是 AM:例如,如果您将时间设置为 07:45,它会将字符串中的时间存储为“7:45”,而不是“ 07:45”,因此代码中的这一行失败:
int hours = Integer.parseInt(Hora.substring(0, 2));
(抛出这个错误,并不是真正需要理解问题):
java.lang.NumberFormatException: Invalid int: "5:"
,因为“子字符串”的位置不再起作用。 (1 位存储在字符串中,而不是 2 位)。分钟也是如此,例如如果我将分钟设置为 08,我的时间选择器将它们存储为 8,然后再次出现相同的问题。
现在我想了两种方法来解决这个问题:要么更改我的 settingsactivity 中的代码并以不同的方式解析字符串,要么更改存储字符串的方式:
if (positiveResult) {
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);
if (callChangeListener(time)) {
persistString(time);
}
setSummary(getSummary());
}
(这些是负责将值保存为字符串的代码行)
我应该如何解决这个问题?
【问题讨论】:
标签: java android string android-preferences timepicker