1

Here's the ListAdapter that I am trying to bind my ListView with.

ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.my_item,c,new String[] {"title","body"},
new int[] { R.id.TextView_Title,R.id.TextView_Body});
setListAdapter(adapter);

This works. But I am stuck at what I guess should be very simple. What I want to do is to display the title completely while I display a sub string of the body (say, first 10/15 chars). How do I do this in this case? Can I manipulate the cursor directly in a way so that it returns a substring at the first place or do I have to do it after the cursor has returned the values (in that case, how?). Thanks for the help.

redGREENblue
  • 3,076
  • 8
  • 39
  • 57

1 Answers1

1

EDIT: OK, sorry I thought you wanted to 'get' the substring of the body column but you want to 'set' it as a substring???

Implement SimpleCursorAdapter.ViewBinder on your activity and override setViewValue().

At some point in your code you'll need to use...

adapter.setViewBinder(this); // Put this on onCreate() perhaps

...and the code would look similar to this...

public class MyActivity extends Activity
    implements SimpleCursorAdapter.ViewBinder {

    @Override
    public boolean setViewValue(View view, Cursor cursor, int column) {
        int bodyColumn = cursor.getColumnIndex("body");
        if (column == bodyColumn) {
            String bodyString = cursor.getString(bodyColumn);
            ((TextView)view).setText(bodyString.subString(0, 10));

            return true; // Return true to show you've handled this column
        }
        return false;
    }
}
Squonk
  • 48,735
  • 19
  • 103
  • 135
  • Sorry if it's a noob question, but how do I bind this two fields to my ListView then? I guess the code here would work fine when I need to return a single or a particular set of rows. I may be wrong (and confused :-) But my list may contain hundred or more items in it. I need to get the sub string and then bind that data with the listview, or if I have to do it this way, then how do I set the adapter? – redGREENblue Mar 29 '11 at 17:11
  • Thanks MisterSquonk. However I couldn't get it to work exactly like this. But this helped me look at the right direction and find a solution. Also, it may be because my Java knowledge is very limited and so I tend to mis up things. Anyway, your answer and this thread here (http://stackoverflow.com/questions/1505751/android-binding-data-from-a-database-to-a-checkbox-in-a-listview) , solved the problem. – redGREENblue Mar 30 '11 at 13:20
  • @redGREENblue: I have to admit I didn't test that exact code but it is very similar to what I use in one of my activities to modify text before it is written to a list item. It's possible I got something slightly wrong but good to know it was close enough to help you find something that works for you. – Squonk Mar 30 '11 at 15:08