Changing values from Cursor using SimpleCursorAdapter

后端 未结 5 1591
半阙折子戏
半阙折子戏 2020-12-01 03:50

I have database table with the columns {Name, Time (UTC format) , Latitude, Longitude}

I display the table using a ListActivity with a SimpleCursorAdapter.

I

5条回答
  •  鱼传尺愫
    2020-12-01 04:09

    Going thru this old post, noticed I have done something similar that might help:

    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);
    }
    

    }

    Usage:

        // 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);
    

    Hope this helps anyone out there !

提交回复
热议问题