0

I have this method that populates ListView from Database. Everything works good. But I want to have one of the textfields showing the value with two decimals.

This has been asked before and many marked is as duplicate but the question is how can I implement the two decimals and where do I do it in the code below

As you can see, I tried many different things without success. Maybe I need to build a custom adapter where I set my TextViews?

And please don't mark this as a duplicate because the answer is not given for etc here:

Best way to Format a Double value to 2 Decimal places

or here:

Round a double to 2 decimal places

or here:

How to round a number to n decimal places in Java

Here comes my code and my question is where can I Implement my code for rounding up to two decimals?

private void populateListViewFromDB(int month, int year) {


    Cursor cursor = dbHandler.getMonth(month,year);

    // TextView setEx = (TextView)findViewById(R.id.oneRowExkl);
    // set = Double.parseDouble(setEx.getText().toString());
    // setEx.setText(String.format("%.2f", set));
    //TextView ex = (TextView)findViewById(R.id.oneRowExkl);
    //ex.setText(String.format("%.2f", Double.parseDouble(MyDBHandler.INKL)));


    String[] fromFieldNames = new String[] {
            MyDBHandler.COLUMN_PRODUCTNAME, MyDBHandler.DATE,
            MyDBHandler.INKL };
    int[] toViewIDs = new int[] { R.id.oneRowName, R.id.oneRowDate,
            R.id.oneRowExkl };

    // Create adapter to may columns of the DB onto element in the UI.
    @SuppressWarnings("deprecation")
    SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, //
    Context  
            R.layout.one_row, // Row layout template
            cursor, // cursor (set of DB records to map)
            fromFieldNames, // DB Column names
            toViewIDs // View IDs to put information in
    );

    ListView myList = (ListView) findViewById(R.id.list1);
    // myList.setBackgroundColor(Color.GRAY);
    myList.setAdapter(myCursorAdapter);
}
Cœur
  • 32,421
  • 21
  • 173
  • 232
Waffles.Inc
  • 2,630
  • 3
  • 11
  • 17

2 Answers2

0

First, what is the datatype in the DB? Is it set to handle decimals/stored as such in DB? Can you change the rounding rules on the DB side?

If not, you want to implement the rounding in code. Since you are using a SimpleCursorAdapter in your example, it uses convertToString(Cursor) to output data to your views.

What you can do is give it a custom string converter, that you create, for the specified column, where you can do the rounding.

For example:

CursorToStringConverter myConverter = new CursorToStringConverter() {

@Override
public CharSequence convertToString(Cursor cursor) {
   int myColumn = [whatever column id];
   String s = cursor.getString(myColumn); //Or .getFloat() for instance
   return [whatever rounding you want, or truncating, or such]
 }
}; 

Then set it on your adapter:

myAdapter.setCursorToStringConverter(myConverter);

You can also try giving the adapter a new ViewBinder, where you check for the desired column and when it is about to be bound, you manually edit the output before binding, like this (paste this in before you assign the adapter to the view):

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

    if (columnIndex == 3) {
            //If it is actually stored as float number in db, do
            //cursor.getFloat(columnIndex) instead
            String formatStr = cursor.getString(columnIndex);
            TextView textView = (TextView) view;

            //Here, do your truncating
            [insert whatever code to either truncate string or format float]

            textView.setText(fixedStr); 
            return true;
     }

     return false;
 }
});

To just see how it works, before doing your truncating or formatting, where it says [insert...] just set:

String fixedStr = "Random string";  

and you'll probably see what it does.

Richard Tyregrim
  • 582
  • 2
  • 12
  • That looks like a good solution, but novice as I am I did not get it to work. – Waffles.Inc Dec 10 '15 at 12:48
  • See my edit for further option... Note that you need to know what it is in db (datatype) so you can call cursor.getFloat() if it is stored as such, or getString() if it is VARCHAR etc. Then you just convert the data in a way you like (format for two decimals). columnIndex is the cursor's active column, so change this number to the one you want (what do you need to format) – Richard Tyregrim Dec 10 '15 at 13:25
  • Ok, I'll try to work with this. And I stored two of them as Strings and the one I need to format as a REAL – Waffles.Inc Dec 10 '15 at 14:30
0

Just to show how the problem was solved with @Richar Erikssons code, here's the code that solved my problem

 myCursorAdapter.setViewBinder(new ViewBinder() {
         @Override
         public boolean setViewValue(View view, Cursor cursor, int 
         columnIndex) {
             if (columnIndex == 3) {


                     TextView textView = (TextView) view;


                     String fixedStr = String.valueOf(String.format("%.2f", 
                     cursor.getDouble(columnIndex)));

                     textView.setText(fixedStr); 
                     return true;
              }

              return false;
          }
         });
Waffles.Inc
  • 2,630
  • 3
  • 11
  • 17