2012-02-15 8 views
0

私はdatetime値を持つフィールドを持っていて、リストビューにフォーマットされた値を表示したいという問題があります。 誰かが自分のコードを見て、このコードを参考にしてもらえますか?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

答えて

3

SimpleCursorAdapterは、実行しようとするものに対しては単純すぎます。 'from'パラメータは実際には列名の配列で、データはカーソルから各行の対応するTextViewに直接マップされます。

私は、TextViewを拡張して、カーソルに格納されているデータを理解し、内部的に書式設定を処理する方法があると言われてきました。しかし、技術的に正しい方法ではない別の方法は次のとおりです。

上記のロジックを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

+0

私は少し遅れましたが、あなたの答えは素晴らしいです!それは素晴らしい作品であり、ありがとう! newView()では、膨らんだレイアウトはリストビューのアイテムレイアウトです.2番目にstartManagingCursorメソッドは廃止され、注意深く処理する必要があります。 – ElaGorilaki

関連する問題