0

In Vaadin 7, is there an easy way to calculate the numeric total for selected columns? I know how to do it for Vaadin 8, defined here. But since Vaadin 7 uses a container, I am trying to think of the best way to do it. Currently, this is the best way I can think of, based on the documentation here. Code is a rough draft, so I expect there are some syntax problems. Treat it more as pseudo code, if possible.

Map<Object,Double> totals = new HashMap();
for (Iterator<?> i = container.getItemIds().iterator(); i.hasNext();) {
    Object itemId = i.next();
                
    Item item = container.getItem(itemId);

    for(Object totalCol : totalColumns)
    {
        Object columnVal = item.getItemProperty(totalCol);
        
        Double total = totals.get(totalCol);
        if(!(total instanceof Double))
            total = 0.0;
        if(columnVal instanceof Double)
        {
            total += (Double)columnVal;             
        }
        else if(columnVal instanceof Long)
        {
            total += (Long)columnVal;
        }
        else if(columnVal instanceof Integer)
        {
            total += (Integer)columnVal;
        }
        else if(columnVal instanceof String)
        {
            try {
                Long value = Long.parseLong((String) columnVal);
                total += value;
            } catch (NumberFormatException e) {
                try {
                    Double value = Double.parseDouble((String) columnVal);
                    total += value;
                } catch (NumberFormatException e1) {
                }
            }
        }

        totals.put(totalCol, total);
    }

    /* At this point, go through totals Map, and set value to correct footer column with correct
     * text formatting.  This part is easy, and clearly documented, so leaving it off this
     * code example.
     */
}

By the way, the above idea works, my question is more if this is the best idea or not?

Tony B
  • 915
  • 1
  • 9
  • 24
  • It looks like a very generic solution. Is it really so, that in your application the actual data can be any of the types? I would assume that in most apps you have just one type of data in the column, and if so then the code can be greatly simplified. E.g. if you can assume everything is integer or so. – Tatu Lund Jul 18 '22 at 10:01
  • Some data elements are Double, some are Long. Data ultimately comes from XML transactions, so starts as String, just sometimes I wrap it and do the conversion from string to Double/Long inside the a bean, sometimes I don't, so I have to handle String as well. Integer is only there out of paranoia, I don't think I actually ever use Integer. Part of the reason why it is so generic is because this is common code, used to load data from various different XML, so was just easier to support all numerics I know I normally support. – Tony B Jul 18 '22 at 17:27

0 Answers0