android - 在 SimpleCursorAdapter 中将毫秒字符串转换为格式化日期字符串

标签 android adapter

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

最佳答案

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);
    }
}

关于android - 在 SimpleCursorAdapter 中将毫秒字符串转换为格式化日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12125366/

相关文章:

android - 自动完成时疯狂的 SQLite 和光标泄漏

java - 如何从 MainActivity 将 url 图像添加到 Adapter ViewPager - Android

android - Horizo​​ntalScrollView 和 Adapter

android - 带有水平 ScrollView 的 ListView

android - 应用程序强制在启动时关闭

android - 在不缩放内部内容的情况下缩放 Android ListView

android - 显示指标减去状态栏?

android - Firebase Auth getCurrentUser() 检索已删除的用户

java - 单击事件后,RecyclerView跳到顶部

Android:具有复杂数据模型的ListView