时间选择器整数错误

Timepicker Integer Error

我的首选项中有一个时间选择器 activity 用于设置应显示通知的时间。该值存储为字符串,例如:“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 会以不同的方式存储值:例如,如果您将时间设置为 07:45,它会将时间存储在字符串中为“7:45 ”,而不是“07:45”,因此代码中的这一行失败:

int hours = Integer.parseInt(Hora.substring(0, 2));

(抛出这个错误,不是真正需要理解的问题):

java.lang.NumberFormatException: Invalid int: "5:"

,因为 "substring" 的职位不再有效。 (1 个数字存储在字符串中而不是 2 个)。分钟也一样,比如我把分钟设置为08,我的timepicker将它们存储为8,同样的问题又出现了。

现在我想到了两种方法来解决这个问题:要么更改设置中的代码activity 并以不同方式解析字符串,要么更改存储字符串的方式:

if (positiveResult) {
        lastHour=picker.getCurrentHour();
        lastMinute=picker.getCurrentMinute();
        String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);

        if (callChangeListener(time)) {
            persistString(time);
        }
        setSummary(getSummary());
    }

(这些是负责将值保存为字符串的代码行)

我该如何解决这个问题?

您可以尝试使用 DateFormatparse 方法来解析您的通知时间字符串。这将 return 一个 Date 对象,您可以使用它来设置 Calendar 对象的 date/time。

类似于:

DateFormat df = new SimpleDateFormat("H:mm"); // construct date formatter to recognize your time pattern
Date myDate = df.parse(pref.getString("notification_time",""));
calendar.setTime(myDate);  // set the time of calendar object

// do other stuff with date here...

这样一来,您就无需为解析时间而烦恼,您可以让现有工具为您完成这项工作。

简单测试:

public class Test {
    public static void main(String[] args) throws Exception {
        DateFormat df = new SimpleDateFormat("H:mm");
        Date myDate = df.parse("17:45");
        System.out.println(myDate.toString());

        Calendar c = Calendar.getInstance();
        c.setTime(myDate);

        int hours = c.get(Calendar.HOUR_OF_DAY);
        int min = c.get(Calendar.MINUTE);

        System.out.println("Hour = " + hours + "\nMin = " + min);
    }
}

产生:

Thu Jan 01 17:45:00 PST 1970
Hour = 17
Min = 45