13 Replies Latest reply on Oct 23, 2010 9:52 PM by dantheinc

    Extracting data from an array in flex 3 output to text file

    dantheinc

      i cant seem to find any information on how to extract data from an array collection to output to a text file.  I have to do this for my flex 3 project.

       

      This is the code i have its in my main file and the array displays to a list in my shopping cart file, there is a button there to save the file to a text file on the desktop but the code just isn't working, would appreciate any help.

       

      public function saveShoppingCart():void
                  {
                     
                      var file:File;
                      var path:String="files/shoppingcart.txt";
                      var stream:FileStream;
                      var i:Number;
                 
                      try
                      {
                          file=File.desktopDirectory.resolvePath(path);
                          //declare a string to add to the file
                          var outputString:String="";
                          //declare variables to get data from equipArray.
                          var name:String, price:Number;
                         
                          for(i=0;i<equipArray.length;i++)
                         
                          {
                              name=equipArray[i].name;
                              price=equipArray[i].price;
                             
                          }
         
                         
                         
                          outputString=name+":"+price;
                          outputString=outputString.replace(/\n/g, File.lineEnding);
                          stream=new FileStream();
                          stream.open(file, FileMode.WRITE);
                          stream.writeUTFBytes(outputString);
                          stream.close();
                         
                      }           
                      catch(error:Error)
                      {
                          compShoppingcart.lblFile=error.message;
                      }
                     
                     
                     
                  }

       

      it goes to shopping cart file via event handling,  if more info is needed, let me know.

        • 1. Re: Extracting data from an array in flex 3 output to text file
          jfb00 Level 3

          Hi,

          For better performance try to take out the lenght out of the for loop.

          Try upper case letters for the field names.

           

                    var myCount:Number = equipArray.length

                    for(i=0;i<myCount; i++)
                              {
                                  name=equipArray[i].NAME;
                                  price=equipArray[i].PRICE;
                                 
                              }

           

          Johnny

          Please rate answers

          • 2. Re: Extracting data from an array in flex 3 output to text file
            dantheinc Level 1

            Hi Jonny,   I put your code into the project and removed my for loop but this error came up.

             

            TypeError: Error #1034: Type Coercion failed: cannot convert "Error #1069: Property NAME not found on valueObjects.BluRayDVD and there is no default value." to mx.controls.Label.
                at main/saveShoppingCart()[J:\_workspace\Sim3\src\main.mxml:128]
                at main/__compShoppingcart_saveCart()[J:\_workspace\Sim3\src\main.mxml:152]
                at flash.events::EventDispatcher/dispatchEventFunction()
                at flash.events::EventDispatcher/dispatchEvent()
                at mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src \mx\core\UIComponent.as:9298]
                at comp::shoppingcart/saveShoppingCart()[J:\_workspace\Sim3\src\comp\shoppingcart.mxml:15]
                at comp::shoppingcart/__btnSave_click()[J:\_workspace\Sim3\src\comp\shoppingcart.mxml:44]

             

            ill try and play with the name and price and see what happens,  if you can think of anything else it would be great.  If you need to see any more of my code please let me know.

             

            Thanks

            Danielle

            • 3. Re: Extracting data from an array in flex 3 output to text file
              jfb00 Level 3

              Hi,

              How do you get the value of equipArray?

              Looks like the array object doesn't have the proper values.

               

              Johnny

              Please rate my answer.

              • 4. Re: Extracting data from an array in flex 3 output to text file
                dantheinc Level 1

                ill give you the main file,   Ive played with it a little and now its outputing to the

                shopping cart.txt file but only one item at a time will not do more than one.

                 

                 

                <?xml version="1.0" encoding="utf-8"?>
                <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="comp.*"
                    creationComplete="getData.send();">
                   
                    <mx:Script>
                        <![CDATA[
                           
                            import mx.rpc.events.FaultEvent;
                            import mx.rpc.events.ResultEvent;
                            import mx.events.ItemClickEvent;
                            import mx.events.CollectionEvent;
                            import mx.collections.ArrayCollection;
                            import valueObjects.*;
                           
                            [Bindable]
                            private var blurayArray:ArrayCollection=new ArrayCollection();
                            [Bindable]
                            private var equipArray:ArrayCollection=new ArrayCollection();
                           
                           
                           
                            private var total:Number=0;
                           
                           
                            private function resultHandler(evt:ResultEvent):void
                            {
                                blurayArray=evt.result.device.bluray.machine;
                                compBluraydvd.dgrBluraydvd.dataProvider=blurayArray;
                            }
                           
                            private function faultHandler(evt:FaultEvent):void
                            {
                                var faultInfo:String="fault code: "+evt.fault.faultCode+"\n\n";
                                faultInfo+="fault string: "+evt.fault.faultString+"\n\n";
                                mx.controls.Alert.show(faultInfo,"Fault Information");       
                            }
                           
                            private function addToBluDisplay():void
                            {
                                var price:Number=Number(compBluraydvd.dgrBluraydvd.selectedItem.Price);
                                var io:String=compBluraydvd.dgrBluraydvd.selectedItem.io;
                                var name:String=compBluraydvd.dgrBluraydvd.selectedItem.ProductName;
                                total=total+price;
                               
                                var theBluRayDVD:BluRayDVD=new BluRayDVD(name,io,price);
                                equipArray.addItem(theBluRayDVD);   
                               
                                compShoppingcart.lstCart.dataProvider=equipArray;   
                                compShoppingcart.lblTotal.text="Total $"+total;
                               
                            }
                            private function addToTvDisplay():void
                            {
                                var price:Number=Number(compTv.dgrTv.selectedItem.Price);
                                var resolution:String=compTv.dgrTv.selectedItem.Resolution;
                                var name:String=compTv.dgrTv.selectedItem.ProductName;
                           
                                total=total+price;
                               
                                var theTv:Tv=new Tv(name,resolution,price);
                                equipArray.addItem(theTv);   
                               
                                compShoppingcart.lstCart.dataProvider=equipArray;   
                                compShoppingcart.lblTotal.text="Total $"+total;
                           
                               
                            }
                            private function addToAudioDisplay():void
                            {
                                var price:Number=Number(compAudio.dgrAudio.selectedItem.Price);
                                var sound:String=compAudio.dgrAudio.selectedItem.Sound;
                                var name:String=compAudio.dgrAudio.selectedItem.ProductName;
                           
                                total=total+price;
                               
                                var theAudio:Audio=new Audio(name,sound,price);
                                equipArray.addItem(theAudio);   
                               
                                compShoppingcart.lstCart.dataProvider=equipArray;   
                                compShoppingcart.lblTotal.text="Total $"+total;
                           
                               
                            }
                            private function saveShoppingCart():void
                            {
                                var file:File;
                                var path:String="files/shoppingcart.txt";
                                var stream:FileStream;
                                var i:Number;
                           
                                try
                                {
                                    file=File.desktopDirectory.resolvePath(path);
                                    //declare a string to add to the file
                                    var outputString:String="";
                                    //declare variables to get data from equipArray.
                                    var name:String, price:Number;
                                   
                                     var myCount:Number = equipArray.length
                                      for(i=0;i<myCount; i++)
                                        {
                                       
                                            name=String(equipArray.removeItemAt(i));
                                            //price=equipArray[i].price;
                                            outputString="\n"+name;
                                            outputString=outputString.replace(/\n/g, File.lineEnding);
                                            stream=new FileStream();
                                            stream.open(file, FileMode.APPEND);
                                            stream.writeUTFBytes(outputString);
                                            stream.close();
                                       
                                            }

                 

                                   
                                  
                                   
                                }           
                                catch(error:Error)
                                {
                                    compShoppingcart.lblFile=error.message;
                                }
                               
                            }
                           
                           
                        ]]>
                    </mx:Script>
                    <mx:HTTPService id="getData" url="xml/bluray.xml" result="resultHandler(event);"
                        fault="faultHandler(event);"/>

                 

                    <mx:Style source="css/sim3.css"/>
                    <mx:VBox width="949" height="702" backgroundColor="#BCAD84" horizontalAlign="center">

                 

                        <mx:Label text="DIRT CHEAP ELECTRONICS" width="518" fontSize="28" fontFamily="Georgia" textAlign="center" fontWeight="bold"/>
                            <mx:LinkBar dataProvider="viewstack1" borderStyle="solid" width="836" fontSize="19" fontFamily="Times New Roman" color="#D52113"/>
                                <mx:ViewStack id="viewstack1" resizeToContent="true" height="600" width="830" creationPolicy="all">
                                       
                                    <ns1:home id="home" label="Home" width="900" height="602"/>
                                    <ns1:bluraydvd id="compBluraydvd" label="BluRaydvd" width="820" height="550" backgroundColor="#ECEEB3" addBluDisplay="addToBluDisplay();"/>
                                    <ns1:tv id="compTv" label="Tv" width="820" height="550" backgroundColor="#F2F3D6"  addTvDisplay="addToTvDisplay();"/>
                                    <ns1:audio id="compAudio" label="Audio" width="820" height="550" backgroundColor="#EFF2A6" addAudioDisplay="addToAudioDisplay();"/>
                                    <ns1:shoppingcart id="compShoppingcart" label="Shopping Cart" width="820" height="550" backgroundColor="#ECEF99" saveCart="saveShoppingCart();"/>
                                       
                                       
                                </mx:ViewStack>
                                   
                   
                    </mx:VBox>
                   
                </mx:WindowedApplication>

                 

                Can you think of anyway to add more than 1 item at a time ie a tv and blu ray item, whenever i try i get the error,

                TypeError: Error #1034: Type Coercion failed: cannot convert "Index '1' specified is out of bounds." to mx.controls.Label.
                    at main/saveShoppingCart()[J:\_workspace\Sim3\src\main.mxml:141]
                    at main/__compShoppingcart_saveCart()[J:\_workspace\Sim3\src\main.mxml:165]
                    at flash.events::EventDispatcher/dispatchEventFunction()
                    at flash.events::EventDispatcher/dispatchEvent()
                    at mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src \mx\core\UIComponent.as:9298]
                    at comp::shoppingcart/saveShoppingCart()[J:\_workspace\Sim3\src\comp\shoppingcart.mxml:15]
                    at comp::shoppingcart/__btnSave_click()[J:\_workspace\Sim3\src\comp\shoppingcart.mxml:44]

                 

                not sure what that means

                 

                regards

                Danielle

                • 5. Re: Extracting data from an array in flex 3 output to text file
                  jfb00 Level 3

                  Lets try this first:

                  REPLACE

                  private function resultHandler(evt:ResultEvent):void
                              {
                                  blurayArray=evt.result.device.bluray.machine;
                                  compBluraydvd.dgrBluraydvd.dataProvider=blurayArray;
                              }

                  WITH

                  private function resultHandler(evt:ResultEvent):void
                              {
                                  blurayArray= ArrayCollection(evt.result);
                                  compBluraydvd.dgrBluraydvd.dataProvider=blurayArray;
                              }

                   

                  That should give you the array as object.

                  Let me know

                   

                  Johnny

                  • 6. Re: Extracting data from an array in flex 3 output to text file
                    Devtron Level 3

                    He had the loop condition better the first time around.

                     

                    for(i=0;i<equipArray.length; i++) {
                          name=equipArray[i].NAME;
                          price=equipArray[i].PRICE;     
                    }

                     

                     

                    jfb00 wrote:

                     

                    Hi,

                    For better performance try to take out the lenght out of the for loop.

                    Try upper case letters for the field names.

                     

                              var myCount:Number = equipArray.length

                              for(i=0;i<myCount; i++)
                                        {
                                            name=equipArray[i].NAME;
                                            price=equipArray[i].PRICE;
                                           
                                        }

                     

                    Johnny

                    Please rate answers






                    1 person found this helpful
                    • 7. Re: Extracting data from an array in flex 3 output to text file
                      dantheinc Level 1

                      It comes up with this error.  What i had to do was put example of xml as well as reading from text file and Inheritance with classes which made things messy,  I do it that way it doesnt read from the xml file properly since blu ray array reads from xml.

                       

                      I put your code in Jonny and it came up with this error, on load up.

                       

                      TypeError: Error #1034: Type Coercion failed: cannot convert mx.utils::ObjectProxy@721b651 to mx.collections.ArrayCollection.
                          at main/resultHandler()[J:\_workspace\Sim3\src\main.mxml:29]
                          at main/__getData_result()[J:\_workspace\Sim3\src\main.mxml:153]
                          at flash.events::EventDispatcher/dispatchEventFunction()
                          at flash.events::EventDispatcher/dispatchEvent()
                          at mx.rpc.http.mxml::HTTPService/http://www.adobe.com/2006/flex/mx/internal::dispatchRpcEvent()[C:\autobuild\3.2.0\framewor ks\projects\rpc\src\mx\rpc\http\mxml\HTTPService.as:290]
                          at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::resultHandler()[C:\autobuild\3.2.0\frameworks\ projects\rpc\src\mx\rpc\AbstractInvoker.as:193]
                          at mx.rpc::Responder/result()[C:\autobuild\3.2.0\frameworks\projects\rpc\src\mx\rpc\Responde r.as:43]
                          at mx.rpc::AsyncRequest/acknowledge()[C:\autobuild\3.2.0\frameworks\projects\rpc\src\mx\rpc\ AsyncRequest.as:74]
                          at DirectHTTPMessageResponder/completeHandler()[C:\autobuild\3.2.0\frameworks\projects\rpc\s rc\mx\messaging\channels\DirectHTTPChannel.as:403]
                          at flash.events::EventDispatcher/dispatchEventFunction()
                          at flash.events::EventDispatcher/dispatchEvent()
                          at flash.net::URLLoader/onComplete()

                       

                      its almost there now i just have the problem of adding more than one at a time to the file.

                       

                      Thanks for your help so far

                      Danielle

                      • 8. Re: Extracting data from an array in flex 3 output to text file
                        jfb00 Level 3

                        FYI,

                        You have a low performance when you include the array.length in the loop.

                         

                        Johnny

                        • 9. Re: Extracting data from an array in flex 3 output to text file
                          jfb00 Level 3

                          Now lets convert the XML data to arrayCollection with this example to follow:

                          http://hillelcoren.com/2008/09/21/flex-tip-convert-xml-to-arraycollection/

                           

                          Johnny

                          • 10. Re: Extracting data from an array in flex 3 output to text file
                            dantheinc Level 1

                            Im sorry Johnny,  but im only doing basic web programming here,  Have no idea where to put that code let alone how to link it up,  its gone a bit beyond me im afraid.

                            Also there is nothing wrong with the data getting into the shopping cart ive put it all into one array collection,  all of the pages including the xml page are going in there smoothly its gettting out onto the text file that is the only problem and ive got is that its not extracting into the text file properly.

                             

                            Thanks for trying

                             

                            Danielle

                            • 11. Re: Extracting data from an array in flex 3 output to text file
                              jfb00 Level 3

                              mmm, let's try soemthing more simple:


                              import mx.rpc.xml.SimpleXMLDecoder;

                              private function resultHandler(evt:ResultEvent):void
                              {

                               var xmlStr:String = evt.result.toString();
                              
                               var xmlDoc:XMLDocument = new XMLDocument(xmlStr);
                              
                               var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
                              
                               var resultObj:Object = decoder.decodeXML(xmlDoc);
                              
                               varriableText.text = resultObj.device.bluray.machine; //or the varriable that you are trying to get.
                              }

                               

                              Johnny

                              • 13. Re: Extracting data from an array in flex 3 output to text file
                                dantheinc Level 1

                                Johnny,

                                 

                                There was no need to go back to the xml array and change it with the help of my instructors it was fixed in the array for the shopping cart.  It was moved to the main page and the code was changed thus:

                                .private function saveShoppingCart():void
                                            {
                                                var file:File;
                                                var path:String="files/shoppingcart.txt";
                                                var stream:FileStream;
                                                var i:Number;
                                           
                                                try
                                                {
                                                    file=File.desktopDirectory.resolvePath(path);
                                                    //declare a string to add to the file
                                                    var outputString:String="";
                                                    //declare variables to get data from equipArray.
                                                    var theData:String;
                                                   
                                                     var arraySize:Number = equipArray.length
                                                      for (i=0;i<arraySize; i++)
                                                        {
                                                       
                                                            theData=String(equipArray.removeItemAt(0));
                                                       
                                                            outputString=outputString+theData+"\n";
                                                           
                                                            }
                                                   
                                                        outputString=outputString.replace(/\n/g, File.lineEnding);
                                                        stream=new FileStream();
                                                        stream.open(file, FileMode.WRITE);
                                                        stream.writeUTFBytes(outputString);
                                                        stream.close();
                                                        compShoppingcart.lblTotal.text=null;
                                                   
                                                }           
                                                catch(error:Error)
                                                {
                                                    compShoppingcart.lblFile=error.message;
                                                }
                                               
                                            }

                                The equals sign in the for loop was removed and a removeitem instruction was used at item 0,  now it writes to the shopping cart txt like it was meant to.

                                 

                                regards

                                Danielle