我正在构建一个包含用户列表的Android应用程序,并且我试图从用户那里获得年龄。
我从json文件中获取了所有数据,并且我收到了这样的生日日期:
"birth_date":"1965-05-07"
现在,我试图解析年,月和日,并从用户那里获得年龄。
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String user_id = c.getString(TAG_USERID);
String birth_date = c.getString(TAG_BIRTH_DATE);
String pic_url_get = c.getString(TAG_IMAGE);
int year = Integer.parseInt(birth_date.substring(0, 4));
int month = Integer.parseInt(birth_date.substring(4, 6));
int day = Integer.parseInt(birth_date.substring(birth_date.length() - 2));
Calendar dateOfYourBirth = new GregorianCalendar(year, month, day);
Calendar today = Calendar.getInstance();
int yourAge = today.get(Calendar.YEAR) - dateOfYourBirth.get(Calendar.YEAR);
dateOfYourBirth.add(Calendar.YEAR, yourAge);
if (today.before(dateOfYourBirth)) {
yourAge--;
}
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_BIRTH_DATE, "Age" + yourAge);
contact.put(TAG_IMAGE, "*******/images/" + user_id + "/" + pic_url_get);
// adding contact to contact list
contactList.add(contact);
}
我收到的错误:
04-19 16:32:20.091: E/AndroidRuntime(19736): Caused by: java.lang.NumberFormatException: Invalid int: "null"
04-19 16:32:20.091: E/AndroidRuntime(19736): at java.lang.Integer.invalidInt(Integer.java:138)
04-19 16:32:20.091: E/AndroidRuntime(19736): at java.lang.Integer.parse(Integer.java:375)
04-19 16:32:20.091: E/AndroidRuntime(19736): at java.lang.Integer.parseInt(Integer.java:366)
04-19 16:32:20.091: E/AndroidRuntime(19736): at java.lang.Integer.parseInt(Integer.java:332)
我该如何解决?
答案 0 :(得分:3)
不要重新发明the wheel:
// replace your birth_date substring calls with this
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime birthDate = fmt.parse(birth_date);
答案 1 :(得分:0)
让我们开始实际从用户(json
对象)获取数据?
你能在这个字符串上放置断点吗
birth_date = c.getString(TAG_BIRTH_DATE);
你得到birthdate
吗?
答案 2 :(得分:0)
您可以使用Android自己的日期格式化程序。
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date birthDate = formatter.parse(birth_date);
http://developer.android.com/reference/java/text/SimpleDateFormat.html