I have a problem with my event handler. I am trying to use URLRequest to load some data from a database. But it's stuck in an infinite loop. Any suggestion of why is it looping, even after all the data is loaded?
The result is pushed into an array.
Code:
public function Listingdetailinfo()
{
somedata = SearchVectorTest.lists;
SrSend = new URLRequest("http://testurl/requestimage.php");
SrSend.method = URLRequestMethod.POST;
Arvariables = new URLVariables ;
SrSend.data = Arvariables;
SaLoader = new URLLoader();
SaLoader.dataFormat = URLLoaderDataFormat.TEXT;
Arvariables.data1 = somedata[0];
SaLoader.load(SrSend);
SaLoader.addEventListener(Event.COMPLETE,Asandler);
function searchVOs( pic:String )
{
this.pic = pic;
}
function Asandler(event:Event):void
{
trace(event.target.data);
// retrieve data from php call
var resultString:String = event.target.data;
trace(event.target.data);
// parse result string as json object and cast it to array
var resultArray:Array = JSON.parse(resultString) as Array;
var len:int = resultArray.length;
trace(resultString);
// create vector of SearchVO
var searchVOs:Array = new Array();
// get the length of the result set
var i:int;
for (i=0; i<len; i++)
{
searchVOs[i] = new Listingdetailinfo();
searchVOs[i].pic = resultArray[i].pic;
myArray.push(searchVOs[i].pic);
}
}
}
I assume your code represents the constructor of Listingdetailinfo class. The reason of your "infinite loop" is that you are creating new instances of this class in
searchVOs[i] = new Listingdetailinfo();
Related
I am trying to parse some static variable that i loaded from another class into this URLloader. I can trace the array with no problem, but not sure why i can't set them as the variables for the URLVariables?
private function Contactyes(event:MouseEvent):void
{
//Here create the parser to php database for interested list
variables:URLVariables;
Sends = new URLRequest("http://localhost/Sendinterested.php");
Sends.method = URLRequestMethod.POST;
Sends.data = variables;
Loaders = new URLLoader();
Loaders.dataFormat = URLLoaderDataFormat.TEXT;
Loaders.addEventListener(Event.COMPLETE,completeHandler);
infodata= SearchVectorTest.lists;
somedata=homepage.infoss;
trace(somedata[0]);
variables.userid = somedata[0].TEXT;
variables.username = somedata[1].TEXT;
variables.useremail = somedata[3].TEXT;
variables.Listingname = infodata[1].TEXT;
variables.Listingid = infodata[0].TEXT;
Homepage.as
public class homepage extends MovieClip {
public static var infoss:Array;
public function homepage(){Mend = new URLRequest("http://localhost/myaccount_1.php");
Mend.method = URLRequestMethod.POST;
variablesss = new URLVariables();
variablesss.username = s7.statusname.text;
Mend.data = variablesss;
nLoader = new URLLoader();
nLoader.dataFormat = URLLoaderDataFormat.TEXT;
nLoader.addEventListener(Event.COMPLETE,Candler);
nLoader.load(Mend);
// handler for the PHP script completion and return of status
function Candler(event:Event):void{
var resultString :String = event.target.data;
// parse result string as json object and cast it to array
var resultArray :Array = JSON.parse( resultString ) as Array;
trace(resultArray[0]);
trace(resultArray[1]);
trace(resultArray[2]);
trace(resultArray[3]);
s7.statusname.text= resultArray[1];
infoss = new Array(resultArray[0],resultArray[1],resultArray[2],resultArray[3]);
}
Thanks for your time
I have searched on google en different pages i found the problem but not the solution.
I have a class i made and that class is called WebServiceController:
public class WebServiceController
{
private var url:String;
private var post:Object=new Object();
private var loader:URLLoader = new URLLoader();
private var postVariable:String="";
private var getVariable:String="";
private var Geladen:Boolean=false;
public function WebServiceController()
{
}
public function postUrlData(u:String,p:Object):String
{
url=u;
post=p;
var urlReq:URLRequest = new URLRequest (url);
var i:int=0;
for(var key:String in post)
{
//trace(key +" = " + post[key]);
if(i==0)
{
// urlVars.key = post[key];
postVariable=postVariable+""+key+"="+post[key];
}
else
{
//urlVars.key = post[key];
postVariable=postVariable+"&"+key+"="+post[key];
}
i++;
}
//trace(postVariable);
var urlVars:URLVariables = new URLVariables(postVariable);
//trace(urlVars);
// Add the variables to the URLRequest
urlReq.data = urlVars;
urlReq.method = URLRequestMethod.POST;
// Add the URLRequest data to a new Loader
//loader.load(urlReq);
// Set a listener function to run when completed
loader.addEventListener(Event.COMPLETE, onLoaderComplete);
// Set the loader format to variables and post to the PHP
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlReq);
function onLoaderComplete(event:Event):void
{
return loader.data;
}
}
Now from my movieclip i call the next function but it says undefined:
var wb:WebServiceController = new WebServiceController();
trace(wb.postUrlData(url,post));
I dont know how to solve this. I tried different things but it keeps saying undefined.
The URLLoader.load call is executed asynchronously so the data has not been returned when you attempt to trace it out in the class that instantiates your WebServiceController class.
To access the data in the parent class, your best bet is probably to dispatch an event from the WebServiceController class when the data has loaded and catch it in the parent class.
WebServiceController:
public function postUrlData(u:String, p:Object):void
{
url=u;
post=p;
var urlReq:URLRequest = new URLRequest (url);
var i:int=0;
for(var key:String in post)
{
//trace(key +" = " + post[key]);
if(i==0)
{
// urlVars.key = post[key];
postVariable=postVariable+""+key+"="+post[key];
}
else
{
//urlVars.key = post[key];
postVariable=postVariable+"&"+key+"="+post[key];
}
i++;
}
//trace(postVariable);
var urlVars:URLVariables = new URLVariables(postVariable);
//trace(urlVars);
// Add the variables to the URLRequest
urlReq.data = urlVars;
urlReq.method = URLRequestMethod.POST;
// Add the URLRequest data to a new Loader
//loader.load(urlReq);
// Set a listener function to run when completed
loader.addEventListener(Event.COMPLETE, onLoaderComplete);
// Set the loader format to variables and post to the PHP
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlReq);
}
private function onLoaderComplete(event:Event):void
{
// We can pass the event on like this
dispatchEvent(event);
}
Parent class:
public function initWebServiceController():void
{
var wb:WebServiceController = new WebServiceController();
wb.addEventListener(Event.COMPLETE, onWebServiceControllerDataLoaded);
wb.postUrlData(url, post);
}
private function onWebServiceControllerDataLoaded(event:Event):void
{
// The event target is the URLLoader instance. We can
// access the loaded data via its data property
trace(URLLoader(event.target).data);
}
I am trying to create a vector from unknown class, but it fails, any ideas about how to do it?
This is what i tried:
var vector:Vector = new Vector(); // throw exception
function base():void{
var vector:Vector.<String> = createVector(String);// throw classCastException
}
function createVector(cls:Class):*{
var array:Array = new Array();
for(var i:int = 0; i < 10; i++){
var element:cls = new cls();
array.push(element);
}
return Vector(array);
}
Vector is expecting a parameter type so you can't do this like you want, but using getQualifiedClassName to get class info you can construct a string that will enable you to call the Vector. constructor using getDefinitionByName :
Ex.
// get class parameter name
var className:String=getQualifiedClassName(String);
// get the Vector class object for the given class
var o:Object=getDefinitionByName("__AS3__.vec::Vector<"+className+">");
// call the constructor
var v:*=o.prototype.constructor(["hello", "world"]);
So your function can be written as:
public function createVector(cls:Class):*{
var cn:String = getQualifiedClassName(cls);
var o:Object = getDefinitionByName("__AS3__.vec::Vector.<"+cn+">");
var array:Array = [];
for(var i:int = 0; i < 10; i++){
var element:* = new cls();
array.push(element);
}
return o.prototype.constructor(array);
}
live example at wonderfl:
http://wonderfl.net/c/pkjs
Based on #Patrick answer I found a working solution.
Check it out:
function createVector(cls:Class):*{
var className:String = getQualifiedClassName(cls);
var vectorClass:Class = getDefinitionByName("__AS3__.vec::Vector.<"+className+">") as Class;
var vector:* = new vectorClass(10);
for(var i:int = 0; i < 10; i++){
var element:MyClass = new cls(); // may be Object or Object extends cls
vector[i] = element;
}
return vector;
}
I am stuck with an issue:
In which I am serializing an array collection to a file, the array collection has two type of items an Image and a class object.
It serialize successfully, but when I de-serialize it, It simply returns array collection of objects and I found my self unable to convert these objects into Images and the class object(this class is defined by myself and having three members, two images and a shape).
I am adding the code which I used:
[Bindable] var objcnvs:ClassCanvas;
protected function btnSave_clickHandler(event:MouseEvent):void
{
//for saving data serializaion
var arrAllSave:ArrayCollection = new ArrayCollection();
for(var i:int = 0;i<arrAll.length; i++)
{
try
{
var tempCon:ConnectImage = arrAll[i];
arrAllSave.addItem({item:arrAll[i], type:"ConnectImage" });
}
catch(er:Error)
{
var tempImage:Image = arrAll[i];
var objImage:ClassImage = new ClassImage(arrAll[i]);
arrAllSave.addItem({item:objImage, type:"Image" });
}
}
// First, generate your ByteArray from the VO.
var byteArray : ByteArray = new ByteArray();
byteArray.writeObject( arrAll );
// Resolve your file location.
//var file : File = File.applicationStorageDirectory.resolvePath( "testFile.ri" );
var mapName:String = txtMapTitle.text;
var file : File = File.applicationStorageDirectory.resolvePath( 'Saved Maps/'+mapName+'.imm' );
if(file.exists == true)
{
lblWarn.text = "Map already Exists. Please enter Defferent Map Title";
}
else if(mapName == "")
{
lblWarn.text = "Please enter a title for Map.";
}
else
{
var fileStream:FileStream = new FileStream();
// Save the file to the given location.
fileStream.open(file, FileMode.WRITE);
fileStream.writeBytes( byteArray );
fileStream.close();
lblWarn.text = "Map Saved successfully";
}
}
protected function btnLoadMap_clickHandler(event:MouseEvent):void
{
// Execute the file load.
var loadFileName:String = "t1";
var request : URLRequest = new URLRequest ( "app-storage:/"+"Saved Maps/"+loadFileName+".imm" );
var receptor : URLLoader = new URLLoader( request );
// Make sure our content is interpreted as a ByteArray.
receptor.dataFormat = URLLoaderDataFormat.BINARY;
receptor.addEventListener( Event.COMPLETE, fileLoadedHandler );
}
private function fileLoadedHandler ( event : Event ) : void
{
// Retrieve the event target, cast as the URLLoader we just created
var loader : URLLoader = event.target as URLLoader;
// Retrieve the loaded data. We know it's a ByteArray, so let's cast it as well.
var data : ByteArray = loader.data as ByteArray;
// Use the ByteArray.readObject method to reconstruct the object.
var obj : Object = data.readObject();
// Cast the object and assign it to our data container.
var loadArrAll:ArrayCollection = obj as ArrayCollection;
}
The last line
var loadArrAll:ArrayCollection = obj as ArrayCollection;
this is the issue. I get the array collection but it has only a list of objects no images and no my class objects (although these are there but I found no way to convert this array collection in previous form when I serialized it.)
class that needs to be serialized/deserialised needs to implement flash.utils.IExternalizable.
public function readExternal(input:IDataInput):void - here you restore object
public function writeExternal(output:IDataOutput):void - here you saving object
best regards
Zain, you have to declare your classes like that:
package com
{
[RemoteClass]
public class myClass
{
public function myClass()
{
}
}
}
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.