gpt4 book ai didi

android - 如何将 EditText 日期拆分为 Calendar 对象的年、月和日整数?

转载 作者:行者123 更新时间:2023-11-29 17:31:21 27 4
gpt4 key购买 nike

我有一个用户从 UI 的 EditText 行上的 DatePicker 输入日期。我想将日期分成年、月和日,这样我就可以将这 3 个元素 bundle 在一起传递。我收到这条致命异常消息“NumberFormatException:Invalid int:”2015“”。所以看起来它不喜欢年份拆分。也许在 2015 年之后有一个空格导致错误。我是什么我想念这里?

部分 Activity 文件:

...
private ListenerEditText fListenerEditText;
private int year;
private int month;
private int day;

Calendar c = Calendar.getInstance();
String dateStr = fListenerEditText.getText().toString();
String[]dateParts = dateStr.split("/");
year = Integer.parseInt(dateParts[2]);
month = Integer.parseInt(dateParts[0]);
day = Integer.parseInt(dateParts[1]);
c.set(year, month, day);
Bundle argsbundle = new Bundle();
argsbundle.putInt("year", c.get(Calendar.YEAR));
...

最佳答案

这是因为“2015”末尾有一个尾随空格。

以下将导致与您看到的相同的崩溃:

    Integer.parseInt("2015 ");

我会做一个这样的方法:

public int safeParseInt(String number) throws Exception {
if(number != null) {
return Integer.parseInt(number.trim());
} else {
throw new NullPointerException("Date string is invalid");
}
}

然后你可以这样做:

try {
year = safeParseInt(dateParts[2]);
month = safeParseInt(dateParts[0]);
day = safeParseInt(dateParts[1]);
} catch (Exception e) {
// SHOW SOME MESSAGE TO THE USER
}

关于android - 如何将 EditText 日期拆分为 Calendar 对象的年、月和日整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814499/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com