Kieran
Kieran

Reputation: 61

Android: Display HTML formatted text in a ListView when loaded from database

I have an SQLite database of items where some of them contain basic HTML such as b and sub tags. I've bound the table to a ListView using a SimpleCursorAdapter. Is there a way to make the ListView format the HTML tags so it displays properly? It seems like the way forward is to get the Cursor to deliver SpannedStrings but I can't work out how to do that.

Upvotes: 2

Views: 4035

Answers (3)

Pepijn
Pepijn

Reputation: 1477

You could use the CursorWrapper class.

CursorWrapper cw = new CursorWrapper(myCursor) {
    public String getString(int columnIndex) {
        String withHTML = super.getString(columnIndex);
        return Html.fromHtml(withHTML).toString();
    }
};

Upvotes: 1

Kieran
Kieran

Reputation: 860

Thanks Ian, this is my final adapter code:

    private class HtmlCursorAdapter extends SimpleCursorAdapter {

    public HtmlCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
    }

    @Override
    public void setViewText (TextView view, String text) {
        view.setText(Html.fromHtml(text),BufferType.SPANNABLE);
    }
}

Upvotes: 3

Ian G. Clifton
Ian G. Clifton

Reputation: 9439

If your data contains only simple HTML tags, they can actually be handled by a TextView by using Html.fromHtml(yourString). That static method returns a Spanned, which can be displayed by a TextView with far less overhead than a WebView.

Upvotes: 1

Related Questions