Cambiar valores desde el cursor usando SimpleCursorAdapter


Tengo una tabla de base de datos con las columnas {Nombre , Hora (formato UTC), Latitud, Longitud}

Muestro la tabla usando una ListActivity con un SimpleCursorAdapter.

Me gustaría que la columna Time muestre la hora en un formato legible por humanos (13-07-2010 10:40) en lugar de en formato UTC (18190109089).

¿Cómo puedo especificar que los valores de column Time necesitan algún filtrado/adaptación?

POSIBLE SOLUCIÓN (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 a CharSequence (convertToString(Cursor cursor). De todos modos no se en que formato debería ser el paramater de retorno CharSequence!

Author: Donal Rafferty, 2010-08-31

5 answers


La forma más sencilla de formatear un valor de cursor es usar 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;
    }
});
 74
Author: Hendrik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-26 09:01:19

También tuve el mismo problema después de una larga lucha finalmente encontré la respuesta:) (ver más abajo)

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;
}
 13
Author: Manas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-26 09:02:36

Puede usar setViewBinder(), o subclase SimpleCursorAdapter y anular bindView().

 4
Author: CommonsWare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-31 13:41:56

Puede usar la sintaxis SQLite en esa columna para dar formato a 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');
 4
Author: Pentium10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-31 13:47:03

Pasando por este viejo post, noté 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 alguien por ahí !

 0
Author: TheChuy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 18:12:46