Конвертировать дату из SQLite и заполнить список - PullRequest
0 голосов
/ 16 февраля 2012

У меня проблема, когда у меня есть поле со значением даты и времени, и я хочу отобразить отформатированное значение в виде списка.Может кто-нибудь взглянуть на мой код и помочь с этим?

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 Ответ

3 голосов
/ 16 февраля 2012

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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...