从SQLite转换日期并填充Listview

时间:2012-02-15 23:21:58

标签: android sqlite listview date time

我遇到一个问题,我有一个带有日期时间值的字段,并希望在列表视图上显示格式化的值。 有人可以看看我的代码并帮助解决这个问题吗?

cursor = db.getAllSms();
startManagingCursor(cursor);
int mTime= cursor.getColumnIndex(DBAdapter.KEY_DATETIME);



    String[] from = new String[cursor.getCount()];
    int[] to = new int[] {R.id.label};
    int counter = 0;
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy HH:mm");

        Date resultdate = new Date(cursor.getLong(mTime));
        String mDateTime = sdf.format(resultdate);
        from[counter] = mDateTime;
        counter++;
    }



    SimpleCursorAdapter users = new SimpleCursorAdapter(this, R.layout.sms_row, cursor, from, to);
    setListAdapter(users);

1 个答案:

答案 0 :(得分:3)

SimpleCursorAdapter对于您正在尝试的内容来说太简单了。 'from'参数实际上是一个列名数组,数据将直接从游标映射到游标中每一行的相应TextView。

我被告知,正确的方法是扩展TextView以了解数据,因为它存储在游标中并在内部处理格式。但是,另一种技术上可能不那么正确的方法如下:

扩展CursorAdapter并将上面的逻辑放入bindView。例如:

class DateTimeCursorAdapter extends CursorAdapter {
    LayoutInflater mInflater;

    private int mTime;
    SimpleDateFormat sdf; 

    DateTimeCursorAdapter(Context context, Cursor cursor)
    {
        super(context, cursor);
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        mTime = cursor.getColumnIndex(DBAdapter.KEY_DATETIME);
        sdf = new SimpleDateFormat("dd MMMM yyyy HH:mm");

    }

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

    public void bindView(View row, Context context, Cursor cursor)
    {
        TextView tvLabel = (TextView) row
                .findViewById(R.id.label);


        Date resultdate = new Date(cursor.getLong(mTime));
        String mDateTime = sdf.format(resultdate);
        tvLabel.setText(mDateTime);         
    }

}

然后:

Cursor c = mDB.getSms();
startManagingCursor(c);
DateTimeCursorAdapter adapter = new DateTimeCursorAdapter(this, cursor);
setListAdapter(adapter);