Search code examples
actionscript-3apache-flexflex4.5flash-builder4.5

How to get all the values of one column and calculate a total


I am making a program where people can create their own food schedule. I also want to calculate the total amount of calories per food schedule.

So first off people can add items to a list which are saved in an arraycollection:

    <s:List includeIn="State2" x="12" y="533" width="428" height="157" dataProvider="{acKoop}"
            enabled="true" change="totalcal(event)">
        <s:itemRenderer>
            <fx:Component>
                <mx:Label text="{data.Type} {data.Kcal}" />
            </fx:Component>
        </s:itemRenderer>
    </s:List>

I want a function that retrieves all the values of data.Kcal and then makes a Sum of it.

public function totalcal(event:Event):void{
            var price:Number=acKoop[event.columnIndex].Kcal;
            total += price;

        }

Solution

  • Here the code of link I was send, maybe will be useful:

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="init()">
    
        <fx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                import mx.controls.Alert;
                [Bindable]
                private var acKoop:ArrayCollection = null;
    
                public function init():void{
                    var arr:ArrayCollection = new ArrayCollection();
                    var obj:Object = new Object();
                    obj.Type = "TYPE1";
                    obj.Kcal = 10;
                    arr.addItem(obj);
                    obj = new Object();
                    obj.Type = "TYPE2";
                    obj.Kcal = 50;
                    arr.addItem(obj);
                    acKoop = arr;
                }
    
                public function totalcal(event:Event):void{
                    var i:Number = 0;
                    for each(var obj:Object in ArrayCollection(List(event.currentTarget).dataProvider)){
                        i = i + obj.Kcal;
                    }
                    Alert.show("Total of Kcal = " + i.toString());
                }
            ]]>
        </fx:Script>
    
        <s:List dataProvider="{acKoop}"
                enabled="true" change="totalcal(event)">
            <s:itemRenderer>
                <fx:Component>
                    <mx:Label text="{data.Type} {data.Kcal}" />
                </fx:Component>
            </s:itemRenderer>
        </s:List>
    </s:Application>
    

    Basically, on the change event I take the dataprovider information from the event, and calculate the TOTAL with the for each loop. I hope this will be useful.