当前位置: 首页 > 面试题库 >

Android-使用游标适配器格式化ListView中的时间戳

宰宣
2023-03-14
问题内容

我正在使用SimpleCursorAdapter填充Android ListView,并且想知道如何将所有从数据库中获得的时间戳(“
DATE_DATE”中的每个时间戳)转换为可读的日期,也许使用SimpleDateFormat?

Cursor programDateCursor = mDbAdapter.loadProgramDates();

startManagingCursor(programDateCursor);

String[] from = new String[]{ "DATE_DATE" };

int[] to = new int[]{ R.id.text1 };

SimpleCursorAdapter programDates = 
             new SimpleCursorAdapter(this, R.layout.program_date,
                                      programDateCursor, from, to);

setListAdapter(programDates);

我在Java方面没有做太多工作,所以有没有更好的方法/任何方法可以做到这一点?除了事先将预先格式化的日期存储在数据库中之外,那是什么?


问题答案:

您将必须创建一个自定义的CursorAdapter才能格式化时间戳。

public class MyAdapter extends CursorAdapter {
    private final LayoutInflater mInflater;

    public MyAdapter(Context context, Cursor cursor) {
        super(context, cursor, false);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
         return mInflater.inflate(R.layout.program_date, parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        long time = cursor.getLong(cursor.getColumnIndex("DATE_DATE")) * 1000L;

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);

        String format = "M/dd h:mm a";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String dateString = sdf.format(cal.getTime());

        ((TextView) view.findViewById(R.id.text1)).setText(dateString);
    }
}

该列表来改变String format自己的喜好是在这里。

然后,您可以将此适配器与

Cursor programDateCursor = mDbAdapter.loadProgramDates();
startManagingCursor(programDateCursor);

setListAdapter(new MyAdapter(this, programDateCursor));


 类似资料:
  • 我有一块碎片。加载的视图的onCreateView方法上的这个片段有一个ListView(a)(在适配器(a)中填充)。但是,此ListView(A)中有另一个ListView(B)。所以现在,我必须调用适配器(B)来填充这个listview(B)。如果我从片段调用它,我会得到一个空指针,如果我从适配器调用它(a),它不会崩溃,但不会工作。 如何调用另一个适配器中的适配器。 这是片段的代码: 其中

  • 问题内容: 我有一个带时间戳字段的mySQL数据库。我正在测试时,目前只有一个项目, 我从数据库中提取并使用 我的最终结果显示为 有人知道为什么吗? 编辑:editedit:忽略该编辑… notepad ++的FTP附加组件超时,很遗憾,当它无法同步时,它不会显示错误。 问题答案: 该函数希望将UNIX时间戳记作为其第二个参数- 这意味着您必须将从数据库获取的日期转换为UNIX时间戳记,可以使用以

  • 我有一个以毫秒为单位的数据,使用CountDown类,我将以这种格式显示时间:天:胡:分钟:秒。如果我做毫秒/1000我有总秒如果我做(毫秒/1000)/60我有总分钟等,但我如何以这种格式显示倒计时:2天:21小时:56分钟:00秒 谢谢

  • For %U, all days in a new year preceding the first Sunday are considered to be in week 0. For %W, all days in a new year preceding the first Monday are considered to be in week 0. In some implementati

  • 问题内容: 有没有一种方法可以将UTC时间格式化为我想要的Java中任意字符串格式?基本上,我在考虑让某个类使用时间戳,然后传递它是字符串,告诉它如何格式化,然后它为我返回格式化的字符串。有没有办法做到这一点? 问题答案: java.text.SimpleDateFormat类以对语言环境敏感的方式提供日期的格式设置和解析。 SimpleDateFormat的javadoc标头是详细信息的很好来源

  • 问题内容: 我正在尝试使用这种格式来格式化当前时间。 输出: 有什么建议? 问题答案: 用 由于Go使用以下常量来格式化日期,请参阅此处