2010-08-31 4 views
27

que tienen tabla de base de datos con las columnas {nombre, la hora (formato GMT), latitud, longitud}Los cambios de valores de cursor utilizando SimpleCursorAdapter

puedo mostrar la tabla utilizando un ListActivity con un SimpleCursorAdapter.

Me gustaría que la columna Hora muestre la hora en un formato legible para personas (13-07-2010 10:40) en lugar de hacerlo en formato UTC (18190109089).

¿Cómo puedo especificar que los valores de la columna Tiempo necesiten algún tipo de filtrado/adaptación?

SOLUCIÓN

posible (con un problema):

SimpleCursorAdapter ofrece el método:

setCursorToStringConverter(SimpleCursorAdapter.CursorToStringConverter cursorToStringConverter); 

para especificar cómo una clase que es capaz de convertir un cursor para CharSequence (ConvertToString (cursor Cursor) . de todos modos no sé en qué formato debe ser el parámetro de retorno CharSequence!

Respuesta

74

La forma más sencilla de f ormato un valor cursor es utilizar SimpleCursorAdapter.setViewBinder (..):

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list, cursor, 
      new String[] { Definition.Item.TITLE, Definition.Item.CREATE_DATE }, new int[] { R.id.title, R.id.createDate}); 

adapter.setViewBinder(new ViewBinder() { 

    public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) { 

     if (aColumnIndex == 2) { 
       String createDate = aCursor.getString(aColumnIndex); 
       TextView textView = (TextView) aView; 
       textView.setText("Create date: " + MyFormatterHelper.formatDate(getApplicationContext(), createDate)); 
       return true; 
     } 

     return false; 
    } 
}); 
+6

Recuerde, 'aColumnIndex' es' la columna en la que se pueden encontrar los datos en el cursor'. Usé 'Cursor.getColumnIndex' para compararlo. – theblang

4

Usted puede utilizar setViewBinder(), o subclase SimpleCursorAdapter y anular bindView().

4

Puede usar la sintaxis SQLite en esa columna para formatear la fecha.

Algo como esto lo hará

SELECT strftime('%d-%m-%Y %H:%M',1092941466,'unixepoch'); 

SELECT strftime('%d-%m-%Y %H:%M',timecol,'unixepoch'); 
13

yo también tenía el mismo problema después de larga lucha por fin encontré la respuesta :) (véase más adelante)

use setViewText (TextView v, String text) 

por ejemplo

SimpleCursorAdapter shows = new SimpleCursorAdapter(this, R.layout.somelayout, accountCursor, from, to) 
{ 
@Override 
public void setViewText(TextView v, String text) { 
super.setViewText(v, convText(v, text)); 
}  
}; 

private String convText(TextView v, String text) 
{ 

switch (v.getId()) 
{ 
case R.id.date: 
      String formatedText = text; 
      //do format 
      return formatedText; 
     } 
return text; 
} 
+1

la solución - código muy bueno;) – fmo

0

Yendo a través de este antiguo puesto, se dio cuenta que he hecho algo similar que podría ayudar:

public class FormatCursorAdapter extends SimpleCursorAdapter { 

protected int[] mFormats; 

public static final int FORMAT_TEXT=0; 
public static final int FORMAT_CURRENCY=1; 
public static final int FORMAT_DATE=2; 

public FormatCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int[] formats, int flags) { 
    super(context, layout, c, from, to, flags); 
    mFormats = formats; 
    ViewBinder viewBinder = new ViewBinder() { 
     @Override 
     public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 
      int formatType = mFormats[columnIndex-1]; 
      switch (formatType) { 
       case FORMAT_CURRENCY: 
        NumberFormat nf = NumberFormat.getCurrencyInstance(); 
        nf.setMaximumFractionDigits(2); 
        ((TextView)view).setText(nf.format(cursor.getDouble(columnIndex))); 
        return true; 
       case FORMAT_DATE: 
        DateFormat df = SimpleDateFormat.getDateTimeInstance(); 
        ((TextView)view).setText(df.format(new Date(cursor.getLong(columnIndex)))); 
        return true; 
      } 
      return false; 
     } 
    }; 
    setViewBinder(viewBinder); 
} 

}

Uso:

// For the cursor adapter, specify which columns go into which views with which format 
    String[] fromColumns = { 
      Table.COLUMN_TITLE, 
      Table.COLUMN_AMOUNT, 
      Table.COLUMN_DATE}; 
    int[] toViews = { 
      R.id.tvTitle, 
      R.id.tvAmount, 
      R.id.tvDate}; 
    int[] formatViews = { 
      FormatCursorAdapter.FORMAT_TEXT, 
      FormatCursorAdapter.FORMAT_CURRENCY, 
      FormatCursorAdapter.FORMAT_DATE}; 

    mAdapter=new FormatCursorAdapter(getContext(),R.layout.item_operation,cursor, 
      fromOpsColumns,toOpsViews,formatViews,0); 
    mListView.setAdapter(mOpsAdapter); 

Espero que esto ayude a cualquiera por ahí!

+0

Esta pregunta fue respondida hace 6 años ... por favor explique qué valor nuevo trae su código? –

Cuestiones relacionadas