我正在从String
数据库中检索毫秒SQLite
,并希望将其转换为格式化日期String
。它基本上可以工作,但不是当我在一个数组中尝试它时(见下文)。它会抛出一个NumberFormatException
。我怎样才能解决这个问题?
adapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor,
new String[] { getDate(Long.parseLong(Database.KEY_DATE), "dd. MMMM yyyy hh:mm:ss") , Database.KEY_NAME },
new int[] {R.id.text1, R.id.text2}, 0);
public static String getDate(Long milliSeconds, String dateFormat){
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
答案 0 :(得分:9)
在从new SimpleCursorAdapter
返回值之前,您无法解析它。这意味着您需要创建自己的SimpleCursorAdapter
类型并覆盖setViewText
。
这样的事情:
adapter = new MySimpleCursorAdapter(this, R.layout.listrow, cursor,
new String[] { Database.KEY_DATE , Database.KEY_NAME },
new int[] {R.id.text1, R.id.text2}, 0);
// ...
public static String getDate(Long milliSeconds, String dateFormat) {
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
return formatter.format(milliSeconds);
}
// In MySimpleCursorAdapter.java:
public class MySimpleCursorAdapter extends SimpleCursorAdapter {
@Override
public void setViewText(TextView v, String text) {
if (v.getId() == R.id.text1) { // Make sure it matches your time field
// You may want to try/catch with NumberFormatException in case `text` is not a numeric value
text = WhateverClass.getDate(Long.parseLong(text), "dd. MMMM yyyy hh:mm:ss");
}
v.setText(text);
}
}