2012-02-15 20 views
0

我有一個問題,我有一個日期時間值的字段,並希望在列表視圖上顯示格式化的值。 有人可以看看我的代碼,並幫助這個嗎?從SQLite轉換日期和填充列表視圖

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); 
+0

是什麼問題? – confucius 2012-02-15 23:44:56

回答

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); 
+0

真棒!非常感謝。 – bond 2012-02-16 00:02:48

+0

我有點晚了,但你的答案很棒!它工作得很好,謝謝你!我只需要添加兩件事:在newView()中,佈局膨脹的是佈局視圖的項目佈局,其次,startManagingCursor方法已被棄用,需要謹慎處理。 – ElaGorilaki 2014-03-20 12:15:51