Flash builder variable from xml - actionscript-3

I would like to ask how to load variables from XML to flash builder. Is it possible? I think that I load variables, but my AS3 is done. I mean that variables from XML are loaded after doing script. Any idea how to do it? Thank for advices

Asumming that you will have this xml (this code works perfectly):
<root>
<child id="1">
<detail>
<detailchild description="detail 1 child"/>
<detailchild description="detail 2 child"/>
</detail>
</child>
OpenXml.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com
/flex/spark" firstView="views.OpenXmlHomeView" applicationDPI="160">
</s:ViewNavigatorApplication>
OpenXmlHomeView
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView" viewActivate="view_activateHandler()">
<fx:Script>
<![CDATA[
import mx.collections.XMLListCollection;
public function view_activateHandler():void{
//Open a XML file
var ldr:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("../source.xml");
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.load(request);
}
private function onLoad(e:Event):void
{
var arr:Array = new Array();
var ldr:URLLoader = URLLoader(e.target);
//XML was loaded then read
var myxml:XML = new XML(ldr.data);
var xmlList:XMLListCollection = new XMLListCollection(myxml.children());
//Loop over XML childs to load a Question Array
for each(var obj:Object in xmlList){
arr.push(obj.#id);
var xmlChildren:XMLList = obj.detail;
for each (var qt:Object in new XMLListCollection(xmlChildren.children())){
arr.push(qt.#description);
}
}
lbl.text = arr.toString();
}
]]>
</fx:Script>
<s:Label id="lbl" />
</s:View>
This code shows:
1, detail 1 child, detail 2 child
You can download this project here.
Note: This is a Flex Mobile project.

Sample XML (message.xml)
<?xml version="1.0" encoding="utf-8" ?>
<category>
<movie date = "13/07/31" genre = "Action">
<title>foo</title>
<rate>4.5</rate>
</movie>
</category>
How to parsing XML to variables?
try this:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class XML_Parsing_Tester extends Sprite
{
private var movieDate:String;
private var movieGenre:String;
private var movieTitle:String;
private var movieRate:Number;
public function XML_Parsing_Tester()
{
var loader:URLLoader = new URLLoader();
loader.load(new URLRequest("message.xml"));
loader.addEventListener(Event.COMPLETE, onLoaded);
}
private function onLoaded(e:Event):void
{
var xml:XML = new XML(e.target.data);
movieDate = xml.movie.#date;
movieGenre = xml.movie.#genre;
movieTitle = xml.movie.title;
movieRate = xml.movie.rate;
}
}
}

Related

AIR app:How to load swf from server

My app structure is below:
(local)
Login.swf
(server)
Main.swf
assets1.swf
assets2.swf
Login.swf -> Main.swf (OK!)
Main.swf -> assets1&2.swf (fail!, downloaded but not trigger complete event)
-progress event: bytes:loaded==total
Why?
How can i load assets from server using Main.swf?
I found somebody say it is crossdomain problem...then how to solve?
var _loader:Loader = new Loader();
var context:LoaderContext = new LoaderContext();
context.allowCodeImport = true;
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete_handler);
_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loader_progress_handler);
_loader.loadBytes(_urlloader.data,context);
Thanks!
BE AWARE:
On mobile it only works on Android... iOS due to a security policy does not permit to load an swf inside another one.
Said that you can surerly load an SWF.
First of all we need to understand if you can download the SWF bytearray using the URLLoader.
if yes you can load the swf in a two step routine..
hope this help :)
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
showStatusBar="false"
creationComplete="downloadSwf()">
<fx:Script>
<![CDATA[
import mx.core.FlexGlobals;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.managers.SystemManager;
import spark.components.Application;
private function downloadSwf():void {
// load the file with URLLoader into a bytearray
sfwLoader.visible = false;
var loader:URLLoader = new URLLoader();
// binary format since it a SWF
loader.dataFormat=URLLoaderDataFormat.BINARY;
loader.addEventListener(Event.COMPLETE, onSWFLoaded);
loader.addEventListener(IOErrorEvent.IO_ERROR, cantConnect);
//load the file
loader.load(new URLRequest("url"));
}
private function cantConnect(e:IOErrorEvent):void
{
var loader:URLLoader=URLLoader(e.target);
loader.removeEventListener(Event.COMPLETE, onSWFLoaded);
loader.removeEventListener(IOErrorEvent.IO_ERROR, cantConnect);
// error handling
return;
}
private function onSWFLoaded(e:Event):void {
// remove the event
var loader:URLLoader=URLLoader(e.target);
loader.removeEventListener(Event.COMPLETE, onSWFLoaded);
loader.removeEventListener(IOErrorEvent.IO_ERROR, cantConnect);
// add an Application context and allow bytecode execution
var context:LoaderContext=new LoaderContext();
context.allowLoadBytesCodeExecution=true;
// set the new context on SWFLoader
sfwLoader.loaderContext = context;
sfwLoader.addEventListener(Event.COMPLETE, loadComplete);
// load the data from the bytearray
sfwLoader.load(loader.data);
}
// your load complete function
private function loadComplete(completeEvent:Event):void {
sfwLoader.removeEventListener(Event.COMPLETE, loadComplete);
var swfApplication:* = completeEvent.target.content;
var sysmgr:SystemManager = (swfApplication as SystemManager);
sysmgr.addEventListener(FlexEvent.APPLICATION_COMPLETE, swfAppComplete);
}
private function swfAppComplete(event:FlexEvent):void {
sfwLoader.visible = true;
var sysmgr:SystemManager = (event.currentTarget as SystemManager);
sysmgr.removeEventListener(FlexEvent.APPLICATION_COMPLETE, swfAppComplete);
var swfApp:Application = (sysmgr.application as Application);
if (!swfApp.hasOwnProperty("version")) {
return;
}
// version is a public property in the main of the loaded application
var verion:String = swfApp["version"];
swfApp.addEventListener(Event.CLOSE, appClose);
}
private function appClose(e:Event):void
{
sfwLoader.unloadAndStop(true);
NativeApplication.nativeApplication.exit();
}
private function closeApp(e:CloseEvent):void
{
try{
(FlexGlobals.topLevelApplication as WindowedApplication).close();
}
catch(e:Error){}
}
]]>
</fx:Script>
<mx:SWFLoader id="sfwLoader"
width="100%" visible="false"
height="100%"/>
</s:WindowedApplication>

Flex 4 - How to load XML file programmatically?

I have done my EmployeeDetails application using HTTPService. But I want to load my XML file programmatically. I tried it using URLLoader and URLRequest. But no luck. I couldn't done it.
Sample code using HTTPService:
<fx:Declarations>
<s:XMLListCollection id="employeeXMLList" filterFunction="xmlListCollectionFilterFun"/>
<s:HTTPService id="employeeService" url="http://localhost/demo/TextXmlFile.xml"
method="POST" result="employeeService_resultHandler(event)"
fault="employeeService_faultHandler(event)"
resultFormat="xml"/>
</fx:Declarations>
<fx:Script>
<![CDATA[
protected function employeeService_resultHandler(event:ResultEvent):void
{
var xmlList:XMLList = XML(event.result).Employee;
employeeXMLList = new XMLListCollection(xmlList);
}
protected function employeeService_faultHandler(event:FaultEvent):void
{
spark.components.Alert.show(event.fault.faultString,"Fault Error Message");
}
]]>
</fx:Script>
It's working well.
Now I change this as follows:
<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"
xmlns:components="components.*"
minWidth="955" minHeight="600"
creationComplete="load()">
<fx:Script>
<![CDATA[
private var request:URLRequest = new URLRequest("http://localhost/demo/TextXmlFile.xml");
//request.contentType = "XML";
//request.method = URLRequestMethod.POST;
private var xmlData:XML;
private var loader:URLLoader = new URLLoader();
private function loadXML(event:Event):void
{
xmlData = new XML(event.target.date);
}
private function load():void
{
loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(request);
}
]]>
</fx:Script>
And I don't know what I am done here. Anyone can tell me the correct way to do this? And Please give me some explanation for that?
My XML:
<?xml version="1.0" encoding="UTF-8"?>
<CompanyEmployees version="1">
<Employee>
<Name>John</Name>
<Id>234</Id>
<DOB>1990/04/02</DOB>
<Designation>Project manager</Designation>
<Department>Mobile</Department>
<DOJ>2008/04/11</DOJ>
<Experience>15</Experience>
<Mobile>9999999999</Mobile>
<Email>john.a#Sybrant.com</Email>
</Employee>
<Employee>
<Name>Adya</Name>
<Id>135</Id>
<DOB>1989/04/21</DOB>
<Designation>Software Engineer</Designation>
<Department>Flex</Department>
<DOJ>2009/05/15</DOJ>
<Experience>5</Experience>
<Mobile>76890678990</Mobile>
<Email>adya#Sybrant.com</Email>
</Employee>
</CompanyEmployees>
UPDATE
private var urlRequest:URLRequest;
urlRequest = new URLRequest("http://localhost/TextXmlFile.xml");
urlRequest.contentType = "XML";
urlRequest.method = URLRequestMethod.POST;
I am getting error like "Access of undefined property urlRequest."
It seems to be typo error.
private var request:URLRequest;
private var xmlData:XML;
private var loader:URLLoader = new URLLoader();
private function loadXML(event:Event):void
{
xmlData = new XML(event.target.data); //Note here data instead of date.
}
private function load():void
{
request = new URLRequest("http://localhost/demo/TextXmlFile.xml");
request.contentType = "XML";
request.method = URLRequestMethod.POST;
loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(request);
}
Reason :
You can only do declare and initialize/instantiate object out side of functions.
Normally compiler expect out side of function should be variable declaration(protected/public/private). So we can't assign value of those at out of function like
request.contentType = "XML";
request.method = URLRequestMethod.POST;
This is exact place where function comes in. Sometime it is possible with static block if all neccessary function and variable should be static.
More details about AS3 Static Block https://www.google.co.in/search?q=static+block+in+as3
or Check out SO Can we use static initializers in a Flex Library?
Check docs: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html

TextFormat working in raw AS3 but not working in Flex

This problem is driving me bananas because it seems to be so simple. I'm trying to apply a text format to a text field created with code and have the formatting remain applied to the textfield if the text changes. The following code works as expected in raw AS3. I've broken down these examples to be as simplistic as possible.
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
public class Testing extends Sprite
{
public function Testing()
{
var tf:TextField = new TextField();
addChild(tf);
tf.border = true;
var tfor:TextFormat = new TextFormat();
tfor.align = 'right';
tfor.size = 30;
tf.defaultTextFormat = tfor;
tf.text = 'Testing';
}
}
}
However, similar code in Flex does not behave the same way. The following code results in the text not being formatted correctly.
<?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="_create(event)">
<fx:Script>
<![CDATA[
import mx.core.UITextField;
import mx.events.FlexEvent;
protected function _create(event:FlexEvent):void
{
var tf:UITextField = new UITextField();
ui.addChild(tf);
tf.border = true;
var tfor:TextFormat = new TextFormat();
tfor.align = 'right';
tfor.size = 30;
tf.defaultTextFormat = tfor;
tf.text = 'Testing';
}
]]>
</fx:Script>
<mx:UIComponent id="ui" width="100%" height="100%" />
</s:Application>
I realize that I could just use a Flex component as the text field and stick formatting on it that way, but this code needs to play nicely with previously written code. Thanks for your help in advance.
Below code may help you: - instead of adding it to UIComponent add it to SpriteVisualElement it will work.
<?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="_create(event)">
<fx:Script>
<![CDATA[
import mx.core.UITextField;
import mx.events.FlexEvent;
protected function _create(event:FlexEvent):void
{
var tf:UITextField = new UITextField();
ui.addChild(tf);
tf.border = true;
var tfor:TextFormat = new TextFormat();
tfor.align = 'right';
tfor.size = 30;
tf.defaultTextFormat = tfor;
tf.text = 'Testing';
}
]]>
</fx:Script>
<s:SpriteVisualElement id="ui" width="100%" height="100%" />
</s:Application>

AS3 - ImageSnapshot - not taking snapshot of entire component

I tried to capture the screenshot of a rendered SWF file(chart) and convert it to image by using the following code. But, the output image contains only some part of the actual chart rendered. It is not capturing entire rendered chart...please help me out...Thanks in advance.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
minWidth="955" minHeight="600"
backgroundColor="white" viewSourceURL="srcview/index.html" initialize="initApp()">
<mx:Script>
<![CDATA[
import mx.core.IUIComponent;
import mx.graphics.ImageSnapshot;
import mx.graphics.codec.PNGEncoder;
import flash.net.FileReference;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.controls.Alert;
private var image:ImageSnapshot = new ImageSnapshot;
private var dataXML:String="<chart labelDisplay='Normal' xAxisName='' yAxisName='' pyAxisName='' syAxisName='' rotateYAxisName='' caption='' subCaption='' baseFont='Regular' baseFontSize='10' baseFontColor='' decimalPrecision='' thousandSeparator=',' decimalSeparator='.' numberPrefix='' numberSuffix='' sNumberPrefix='' sNumberSuffix='' bgColor='' showBorder='1' YAxisMinValue='' YAxisMaxValue='' pyAxisMinValue='' pyAxisMaxValue='' syAxisMinValue='' syAxisMaxValue='' showLabels='1' showValues='1' showLegend='Y' legendPosition='Right'><categories><category label='Unmapped'/><category label='FY 2002 - 03'/><category label='FY 2003 - 04'/><category label='FY 2004 - 05'/><category label='FY 2005 - 06'/><category label='FY 2006 - 07'/><category label='FY 2007 - 08'/><category label='FY 2008 - 09'/><category label='FY 2009 - 10'/><category label='FY 2010 - 11'/></categories><dataset seriesName='Base Amount'><set value='-65770'/><set value='71461203'/><set value='66548822'/><set value='87063456'/><set value='261797187'/><set value='282962118'/><set value='3830823027'/><set value='16001588683'/><set value='22514728943'/><set value='23822586701'/></dataset></chart>";
private function initApp():void
{
chart_1.source="MSCombi2D.swf?chartWidth=100&chartHeight=100&registerWithJS=1&dataXML="+dataXML;
}
private function takeSnapshot(source:IBitmapDrawable):void {
// var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(source);
// var imageByteArray:ByteArray = imageSnap.data as ByteArray;
// var str:String = imageByteArray.
// swfLoader.load(imageByteArray);
var imageBitmapData:BitmapData = ImageSnapshot.captureBitmapData(source);
swfLoader.source = new Bitmap(imageBitmapData);
// take a screen capture
// image = ImageSnapshot.captureImage(source, 72, new PNGEncoder(), false);
// var fileSave:FileReference = new FileReference();
// fileSave.save(image.data, "saveImage.png");
}
]]>
</mx:Script>
<mx:ApplicationControlBar dock="true">
<mx:Button label="Take snapshot of DataGrid"
click="takeSnapshot(chart_1);" />
</mx:ApplicationControlBar>
<mx:HBox>
<mx:SWFLoader id="chart_1" />
<mx:SWFLoader id="swfLoader">
<mx:filters>
<mx:DropShadowFilter />
</mx:filters>
</mx:SWFLoader>
</mx:HBox>
I got the answer...i changed the code for the function "takeSnapshot" as follows:
private function takeSnapshot(source:IBitmapDrawable):void
{
var bitmapData:BitmapData = new BitmapData( 1350, 700 );
bitmapData.draw( IBitmapDrawable( chart_1 ));
var swfBitmap:Bitmap = new Bitmap( bitmapData );
var jpg:JPEGEncoder = new JPEGEncoder(100);
var ba:ByteArray = jpg.encode(swfBitmap.bitmapData);
var fileSave:FileReference = new FileReference();
fileSave.save(ba, "saveImage.jpg");
}

Flash builder Access of undefined property issue

I am trying to run the simple code as following:
<fx:Script>
<![CDATA[
import flash.display.*;
import flash.net.URLRequest;
var url2:String = "image2.jpg";
var urlRequest:URLRequest = new URLRequest(url2); //problem code
var loader:Loader = new Loader(); //problem code
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete); //problem code
loader.load(urlRequest);
addChild(loader);
function loader_complete(evt:Event):void {
var target_mc:Loader = evt.currentTarget.loader as Loader;
target_mc.x = (stage.stageWidth - target_mc.width) / 2;
target_mc.y = (stage.stageHeight - target_mc.height) / 2;
}
]]>
</fx:Script>
However, I got errors saying
'access of undefined property 'loader_complete'
'access of undefined property 'loader'
'access of undefined property 'loader'
'access of undefined property 'loader'
'access of undefined property 'urlReguest'
I haven't used Flash builder for a while and need some assistants. Any thoughts? Thanks for the help.
You are attempting to execute code in the class definition.
Executable code should be called from a function, such as creation complete in the Flex component lifecycle:
<?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"
creationComplete="creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import flash.display.*;
import flash.net.URLRequest;
import mx.events.FlexEvent;
public var url2:String = "image2.jpg";
public var urlRequest:URLRequest = new URLRequest(url2); //problem code
public var loader:Loader = new Loader(); //problem code
protected function creationCompleteHandler(event:FlexEvent):void
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete); //problem code
loader.load(urlRequest);
addChild(loader);
}
protected function loader_complete(evt:Event):void
{
var target_mc:Loader = evt.currentTarget.loader as Loader;
target_mc.x = (stage.stageWidth - target_mc.width) / 2;
target_mc.y = (stage.stageHeight - target_mc.height) / 2;
}
]]>
</fx:Script>
</s:Application>