2

我正在String从我的SQLite数据库中检索毫秒,并希望将其转换为格式化的 date 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());
}
4

1 回答 1

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);
    }
}
于 2012-08-25T20:36:18.933 回答