作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个用户从 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/
我是一名优秀的程序员,十分优秀!