sqlite 将时间从数据库转换为ListView时出现问题

qkf9rpyu  于 2023-04-21  发布在  SQLite
关注(0)|答案(3)|浏览(149)

我需要将数据库中的Time字段(毫秒)转换为“MMM dd,yyyy HH:mm”,并列出以升序显示的列表视图,我很难让DateTime显示在我的列表视图上。下面是我使用的代码:
DB:

public Cursor getUserDateTimeLocations(long rowId) throws SQLException
        {
        Cursor mCursor =
            db.query(true, DATABASE_TABLE_LOCATION, new String[] {KEY_ROWID,
                    KEY_LATITUDE, KEY_LONGITUDE, KEY_DATETIME,KEY_USERID,KEY_OBS}, KEY_USERID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

Listview现在我可以显示DateTime字段,但我需要转换每一行的字段,然后显示它,这我不知道如何做到这一点:

private void dateTime() {
    cursor = db.getUserDateTimeLocations(mLocationRowId);
    startManagingCursor(cursor);
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
    mTime= cursor.getLong(3);
    Date resultdate = new Date(mTime);
    String mDateTime = sdf.format(resultdate);
    //Toast.makeText(this, mDateTime, Toast.LENGTH_LONG).show();

    String[] from = new String[] { DBAdapter.KEY_DATETIME};<--How to do it here?
    int[] to = new int[] {R.id.label};

    SimpleCursorAdapter locations = new SimpleCursorAdapter(this, R.layout.user_row, cursor, from, to);
    setListAdapter(locations);

}
ukdjmx9f

ukdjmx9f1#

如果这是SimpleCursorAdapter中唯一特殊的部分,下面的代码会有所帮助。在setListAdapter调用之前添加以下代码:

locations.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

        @Override
        public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) {
            if (columnIndex == 1) {
                TextView textView = (TextView) view;

                long millis = cursor.getLong(columnIndex);
                textView.setText(yourFormattingOfMillisToDateHere);

                return true;
            }

            return false;
        }

    } );
p4tfgftt

p4tfgftt2#

你所要做的就是在CursorAdapter中覆盖setViewText。我的代码中有几行解决了同样的问题:

private class MyCursorAdapter extends SimpleCursorAdapter {

    public MyCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);

    }

    private Date d = new Date();

    @Override
    public void setViewText(TextView v, String text) {
        if (v.getId() == R.id.TrackTime) {
            d.setTime(Long.parseLong(text));
            text = d.toLocaleString();
        }
        super.setViewText(v, text);
    }
}
zbdgwd5y

zbdgwd5y3#

看起来你可能需要滚动你自己的适配器。SimpleCursorAdapter就是这样--一种将字段从数据库绑定到某种类型的文本视图的简单方法。

相关问题