Modifying SimpleCursorAdapter's data
Asked Answered
C

1

16

I'm working on a TV Guide app which uses a ListActivity showing the TV shows for one channel / one day at a time. I'm using a RelativeLayout for the ListView items and I want the ListView to look something like this:

07:00 The Breakfast Show
      Latest news and topical reports
08:00 Tom and Jerry
      More cat and mouse capers

I get the data for the ListView items using the following code:

Cursor cursor = db.rawQuery(SELECT blah,blah,blah);
String[] columnNames = new String[]{"start_time","title", "subtitle"};
int[] resIds = new int[]{R.id.start_time_short, R.id.title, R.id.subtitle};
adapter = new SimpleCursorAdapter(this, R.layout.guide_list_item, cursor, columnNames, resIds);

My problem is that the start_time field is a datetime with the following format:

2011-01-23 07:00:00

so what I get is this:

2011-01-23 07:00:00 The Breakfast Show
                    Latest news and topical reports
2011-01-23 08:00:00 Tom and Jerry
                    More cat and mouse capers

What I'd like to do is format the above using SimpleDateFormat("HH:mm") so I only get the hour:minute part of the start_time field.

I've found the SimpleCursor.ViewBinder interface which suggests it may be what I want but I can't figure out how to use it. If I'm right about ViewBinder, I'd appreciate some pointers to sample code on how to use it. Otherwise, how else can I achieve changing the start_time field to simply show HH:mm format?

Comras answered 23/1, 2011 at 22:17 Comment(0)
H
28

You can do something like this:

adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
    @Override
    public boolean setViewValue(View view, Cursor cursor, int column) {
        if( column == 0 ){ // let's suppose that the column 0 is the date
            TextView tv = (TextView) view;
            String dateStr = cursor.getString(cursor.getColumnIndex("name_of_the_date_column"));
            // here you use SimpleDateFormat to bla blah blah
            tv.setText(theFormatedDate);
            return true;
        }
        return false;
    }
});
Harriet answered 23/1, 2011 at 22:25 Comment(3)
Thank you, that explains it very well. I re-worked your example to fit my code and it's working perfectly for me.Comras
This just saved my butt trying to re-order the row counts from a Cursor, so thank you sir. My code is as follows: HistoryAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int column) { if (column == 0) { // let's suppose that the column 0 is the // date TextView tv = (TextView) view; String rownum = String.valueOf(cursor.getPosition() + 1); // here you use SimpleDateFormat to bla blah blah tv.setText(rownum); return true; } return false; } });Libbie
@Harriet Please, do you think you could help with this #27257916?Paley

© 2022 - 2024 — McMap. All rights reserved.