2

I use the following SimpleCursorAdapter:

String campos[] = { "nome_prod", "codbar_prod",
        "marca_prod", "formato_prod", "preco"};
int textviews[] = { R.id.textProdName, R.id.textProdCodBar, R.id.textProdMarca,
        R.id.textProdFormato, R.id.textProdPreco };
CursorAdapter dataSource = new SimpleCursorAdapter(this, R.layout.listview,
        c_list, campos, textviews, 0);

And this works fine. But "preco" from "campos[]" comes from a double value. Can I format this somehow so my cursor (which feeds a listview) will display this double with two digits after the point (like a money value)?

Can I do it in some simple way, like using "%.2f" somewhere, or will I have to subclass CursorAdapter?

Thanks in advance.

jRicardo
  • 804
  • 10
  • 20

1 Answers1

4

You don't need to subclass CursorAdapter. Simply create a ViewBinder and attach it to the adapter, it will transform the value of a specific column of the cursor. Like so:

dataSource.setViewBinder(new ViewBinder() {
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

        if (columnIndex == 5) {
                Double preco = cursor.getDouble(columnIndex);
                TextView textView = (TextView) view;
                textView.setText(String.format("%.2f", preco));
                return true;
         }
         return false;
    }
});
Majix
  • 1,702
  • 1
  • 16
  • 8
  • Seems to do exactly what I want, but I got this error: 'java.util.IllegalFormatConversionException: %f can't format java.lang.String arguments ' – jRicardo Jul 30 '12 at 19:31
  • 1
    use cursor.getDouble(columnIndex) to get the double value and feed to your string formatter. If you're formatting an amount, recommend using a CurrencyFormatter instead of String.format. – CSmith Jul 30 '12 at 19:36
  • Awesome. Thanks Majix and CSmith. – jRicardo Jul 30 '12 at 19:39
  • Fixed the answer with CSmith's suggestion to use cursor.getDouble instead. – Majix Jul 30 '12 at 19:51