How to migrate AS2 to AS3.? - actionscript-3

How to convert ActionScript 2.0 code to ActionScript 3.0
this is code :
//***********************************************************
var theXML:XML = new XML();
theXML.ignoreWhite = true;
theXML.onLoad = function() {
var nodes = this.firstChild.childNodes;
for (i=0;i<nodes.length;i++){
theList.addItem(nodes[i].firstChild.nodeValue,i);
}
}
theXML.load("http://localhost/conn.php");
//***********************************************************
This is my PHP code that echo's an XML string :
echo "<?xml version=\"1.0\"?>\n";
echo "<name>\n";
while ( $line = mysql_fetch_assoc($res) )
{ echo "<item>" . $line["name"] . "</item>\n"; }
echo "</name>\n"
Using AS3, how do I parse the XML string as actual XML data with nodes?

There are many examples of how to work with XML in AS3, and how to migrate AS2 to AS3.
This would be the equivalent of what you posted:
var loader:URLLoader = new URLLoader();
loader.load(new URLRequest("http://localhost/conn.php"));
loader.addEventListener(Event.COMPLETE, loaderComplete);
function loaderComplete(e:Event):void {
XML.ignoreWhitespace = true;
var xml:XML = new XML(loader.data);
var nodes:XMLList = xml.child(0).children();
for (var i:int = 0; i < nodes.length(); i++) {
theList.addItem(nodes[i].child(0).text());
}
}
Note that in AS3 you can reference XML nodes by name, for example xml.gallery.image[3].url instead of xml.child(0).children()[3].child(0), etc.

Related

How to parse JSON in AS3

I'm trying to build an application in Flash, but I have a problem. I'd like to parse the JSON from an web URL.
link: JSON text to parse
I'd like to get the JSON string "title" from here. Is there a way I can do it?
It says undefined.
var VidDataLoader = new URLLoader();
var VidUrl = "THEURL" + param1.getString(0);
trace(VidUrl)
VidDataLoader.load( new URLRequest(VidUrl))
VidDataLoader.addEventListener(Event.COMPLETE, doneit)
function doneit(e:Event){ var myData:Object = JSON.parse(VidDataLoader.data);
You are trying to reach the data from the VidDataLoader class, but the loaded data is part of the event object:
public function JSONLoader() {
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, decodeJSON);
loader.load(new URLRequest("myfile.json"));
}
// use the event to get the data
private function decodeJSON(e:Event):void {
var loader:URLLoader = URLLoader(e.target) ;
var jsonObject:Object = JSON.parse(loader.data);
}

Convert Actionscript 3 to Actionscript 2

I have an problem to convert AS3 to AS2
Here is my AS3 code
submit.addEventListener("mouseDown", sendData);
function sendData(evt:Event)
{
//for those using PHP
var students:URLRequest = new URLRequest("http://localhost/phpflash/new_student.php");
students.method = URLRequestMethod.POST;
var posts:URLVariables = new URLVariables();
posts.Fullname = Fullname.text;
students.data = posts;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(students);
}
Like #VC.One said, you must learn AS3, AS2 was dropped and actually Flash CC does not support it.
I do not code in AS2 since many, many years. So this code could contain some errors:
submit.onMouseDown = sendData;
function sendData():Void
{
var vars:LoadVars = new LoadVars();
vars.Fullname = Fullname.text;
var target:Object = new Object();
target.onLoad = function(){
trace("vars sended");
}
vars.sendAndLoad("http://localhost/phpflash/new_student.php", target, "POST");
}

ActionScript RSS Title issue

The below AS# RSS reader code pull the titles from the RSS items but seem to include the XML markup as well. How does one not include the XML markup without using Regex or string replace?
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.URLLoader;
import flash.events.IOErrorEvent;
//Read RSS feeds
var RSS_xmlData: XML = new XML();
var xmlLoader: URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("http://www.oshawa.ca/news_rss.asp"));
function LoadXML(e:Event):void {
dtext.text="Loading...";
RSS_xmlData = new XML(e.target.data);
pullFeed(RSS_xmlData);
}
function pullFeed(rss: XML):void {
var str: String="";
str = rss.channel.item.title;
str = str.replace(/\s*\n/g," | ");
//str = str.replace(/'/g,"\"");
//// shows specific entry
var items: Array = new Array();
items = str.split("|");
var tf: TextField = dtext;
var i:Number=0;
var myTimer:Timer = new Timer(4000,1000);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
tf.text = items[i].toString();
scaleTextToFitInTextField(tf);
i = i < items.length - 1 ? i + 1 : 0;
}
myTimer.start();
}
function scaleTextToFitInTextField(txt: TextField):void {
var f: TextFormat = txt.getTextFormat();
f.size = (txt.width > txt.height) ? txt.width : txt.height;
txt.setTextFormat(f);
while (txt.textWidth > txt.width - 4 || txt.textHeight > txt.height - 6) {
f.size = int(f.size) - 1;
txt.setTextFormat(f);
}
}
function onIOError(e:IOErrorEvent):void
{
trace(e.toString());
dtext.text="Finding Feed...";
}
Thanks for any help with this.
The reason you're getting the XML markup in there is because the value returned by rss.channel.item.title is of type XMLList, corresponding to all the <title> nodes matched by that selection - rather than just the text content of those nodes. As you've noted, it's rather backwards to convert that to a String and then strip out the extraneous mark-up manually.
I would iterate over all the <item> nodes and add their <title> content to the array as you go along. The new pullFeed method would then look like:
function pullFeed(rss: XML):void {
var items:Array = new Array(); //Declare Array of titles
var numItems:int = rss.channel.item.length(); //Capture number of <item> nodes
for (var i:int = 0; i < numItems; i++) {
items.push(String(rss.channel.item[i].title)); //Add each <item>'s <title> to the Array
}
var tf: TextField = dtext;
var i:Number=0;
var myTimer:Timer = new Timer(4000,1000);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
tf.text = items[i];
scaleTextToFitInTextField(tf);
i = i < items.length - 1 ? i + 1 : 0;
}
myTimer.start();
}
One other benefit of iterating through the XML nodes this way is that you could easily capture the <description> or <pubDate> content of each <item> on the same pass through the XML, if you planned to make use of that later.

AS3 Adobe AIR: Return xml string

I'm working in Flash CS6 with Adobe AIR 3.3 (for iOS) and having trouble returning an XML string to a textField.
It is tracing the proper information, and I've tried a few ways to return the trace but can't seem to quite get it... Here is my most recent try. Any suggestions? Thanks in advance.
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("http://www.someURL.php"));
//php file that echos xml
myLoader.addEventListener(Event.COMPLETE, init);
var fadedText:TextField;
var touchList:TouchList;
var textOutput:TextField;
var animateLeft:Tween;
var listArray:Array;
var item:TouchListItemRenderer;
var theXML:XML;
var days:Array = new Array("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday");
var daySelected;
var businessNameArray:Array = new Array();
var businessLogoArray:Array = new Array();
var businessAddress:Array = new Array();
var distanceArrayDisplay:Array = new Array();
var distanceArrayCount = 0;
function init(e:Event = null):void
{
trace(myLoader.data);
theXML = new XML(e.target.data);
theXML.ignoreWhitespace = true;
myLoader.close();
// add our list and listener
var itemSizeCalculator = stage.stageHeight / 6;
touchList = new TouchList(stage.stageWidth, stage.stageHeight-itemSizeCalculator);
touchList.addEventListener(ListItemEvent.ITEM_SELECTED, handlelistItemSelected);
addChild(touchList);
touchList.x = stage.stageWidth;
// Fill our list with item rendreres that extend ITouchListRenderer.
for(var i:int = 0; i < theXML.food.length(); i++) {
if(theXML.food[i].monday != "un")
{
item = new TouchListItemRenderer();
item.index = i;
item.data = theXML.food[i].business;
item.name = theXML.food[i].business;
item.addEventListener(MouseEvent.CLICK, itemWasClicked);
item.itemHeight = itemSizeCalculator;
businessNameArray[i]= theXML.food[i].business;
businessLogoArray[i]=("http://www.logosURL.com/"+theXML.food[i].logo);
businessAddress[i]= theXML.food[i].address;
var fadedTextFormat:TextFormat = new TextFormat();
fadedTextFormat.bold = true;
fadedTextFormat.color = 0x999999;
fadedTextFormat.size = 14;
fadedTextFormat.font = "Helvetica";
fadedText = new TextField();
fadedText.height = 30;
fadedText.mouseEnabled = false;
fadedText.defaultTextFormat = fadedTextFormat;
item.addChild(fadedText);
fadedText.x = 75;
fadedText.y = 10;
distanceArrayDisplay.push(fadedText);
var distanceLoader:URLLoader = new URLLoader();
distanceLoader.load(new URLRequest("http://maps.googleapis.com&origins=someAddress&destinations="+businessAddress[i]+"&mode=walking&language=en-en&sensor=false"));
distanceLoader.addEventListener(Event.COMPLETE, distanceCalculated);
var logoLoader:Loader = new Loader();
item.addChild(logoLoader);
var logoURL:URLRequest = new URLRequest("http://www.myLogos.com/"+theXML.food[i].logo);
logoLoader.load(logoURL);
logoLoader.scaleX = .4;
logoLoader.scaleY = .4;
logoLoader.y = logoLoader.y + 5;
logoLoader.mouseEnabled = false;
var arrowGraphic:rightArrow = new rightArrow();
item.addChild(arrowGraphic);
arrowGraphic.x = stage.stageWidth - 5;
arrowGraphic.y = item.height/2;
touchList.addListItem(item);
}
}
}
function distanceCalculated(e:Event)
{
// trace(e.currentTarget.data);
var distanceXML:XML = new XML(e.target.data);
distanceXML.ignoreWhitespace = true;
var returnVar:String = (distanceXML.row.element.distance.text);
distanceArrayDisplay[distanceArrayCount].text = returnVar;
trace(returnVar);
distanceArrayCount++;
}
I am guessing that you are correctly reading the first XML, and that XML has a list of URLs that you want to load and then display some info from those on TextFields. Without knowing the structure of that XML I can't suggest you any working code, but I can point you on the right direction. For more info on reading/iterating XML on flash as3, please read: http://www.kirupa.com/developer/flashcs3/using_xml_as3_pg1.htm
//iterator var
var xml_read:uint=0;
//array of textfields for reference
var array_textFields:Array;
//config XML complete
function init(e:Event = null):void
{
array_textFields = new Array();
theXML = new XML(e.target.data);
theXML.ignoreWhitespace = true;
//this depends on the XML structure, please look at the article I linked
//for more info on how to iterate an XML
var i:uint=0;
for(someUrl in theXML..url)
{
var fadedText:TextField = new TextField();
//you should place each Textfield on different coord, otherwise
//they will all stack on top of each other and you will only see one
//for example:
fadedText.y = (fadedText.height+10)*i;
item.addChild(fadedText);
array_textFields.push(fadedText);
var distanceLoader:URLLoader = new URLLoader();
distanceLoader.load(new URLRequest(someUrl));
distanceLoader.addEventListener(Event.COMPLETE, distanceCalculated);
i++;
}
}
function distanceCalculated(e:Event):void
{
var distanceXML:XML = new XML(e.target.data);
distanceXML.ignoreWhitespace = true;
//retrieve information
var returnVar:String = (distanceXML.row.element.distance.text);
//set to textfield
TextField(array_textFields[xml_read]) = returnVar;
//increase iterator
xml_read++;
}
Please bear in mind that in ActionScript3, all network I/O is asynchronous. Usually EventListener functions don't return any value because you don't know when the data is ready. What you do is store a reference to where you want the data to go (in your case, a TextField variable) when the EventListener function is called asynchronously.

Object Data Type in AS3 and Flash Builder 4.5.1

I am trying to save a Sprite object as a file on the device I'm working on and it seems to work. the problem I'm having is reading the saved file back and placing it back on stage as a sprite. Below is the code I have so far, could someone tell me what it is I'm doing wrong? I have a suspicion that the saved isn't what I expect it to be since the file sizes have been under a kilobyte.
public function save_album(e:Event):void
{
var outFile:File = File.documentsDirectory; // dest folder is desktop
outFile = outFile.resolvePath("canvas3.bin");
var fs:FileStream = new FileStream();
var bytes:ByteArray = new ByteArray();
//trace (File.documentsDirectory.url + "/canvas2.bin");
fs.open(outFile, FileMode.WRITE);
bytes.writeObject(graffitiContainer) //graffitiContainer is a Sprite
bytes.position = 0;
fs.writeBytes(bytes, 0, bytes.length);
fs.close();
}
public function open_album(e:Event):void
{
var inBytes:ByteArray = new ByteArray();
var inFile:File = File.documentsDirectory;
inFile = inFile.resolvePath("canvas3.bin"); // name of file to read
var inStream:FileStream = new FileStream();
inStream.open(inFile, FileMode.READ);
inStream.readBytes(inBytes, 0, inBytes.length);
inStream.close();
inBytes.position = 0;
ui.removeChild(graffitiContainer);
var obj:Sprite = inBytes.readObject() as Sprite; //returns a null
graffitiContainer = obj;
ui = new UIComponent();
graffitiContainer.x = 0;
graffitiContainer.y = 100;
ui.addChild(graffitiContainer);
}
Not fully sure I understand what you're trying to accomplish; however, this implementation doesn't do what you're thinking - writeObject could only serialize general public properties, and not the graphics member.
You could render it to a Bitmap.
Saw a blog post about this:
http://jacwright.com/201/serializing-display-objects/