How to separate URL response data in ActionScripts3 - actionscript-3

I'm working on a site that response to GET request in simple text format, I want to save data and title in separate variables.
Code:
function URLRequest_method():void
{
var url:String = "http://sms-reg.ru/index.php";
var getbalance:String = "mode=api&apikey=*=getbalance";
var postParams:URLVariables = new URLVariables(getbalance);
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.GET;
request.data = postParams;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onLoaderComplete);
urlLoader.load(request);
}
function onLoaderComplete( event:Event ):void
{
var urlLoader2:URLLoader = event.target as URLLoader;
txt_BALANCE1.text = urlLoader2.data;
trace( urlLoader2.data);
//var json:Object = JSON.parse( urlLoader2.data );
// trace( "json.response = ", json.response );
}
URLRequest_method();
Update:
function onLoaderComplete( event:Event ):void
{
var urlLoader2:URLLoader = event.target as URLLoader;
trace( urlLoader2.data );
//var json:Object = JSON.parse( urlLoader2.data );
// trace( "json.response = ", json.response );
var response:String = urlLoader2.data;
var pattern:RegExp = new RegExp("BALANCE:([0-9.-]+)");
var data:Object = pattern.exec(response);
if (data != null && data[1] != null)
{
var value:Number = parseFloat(data[1]);
trace(value);
}
}
Outputs:
BALANCE:123.00
ID23:3(Telegram);ID28:4(Viber);ID29:6(Whatsapp);ID30:5(Instagram);
I need to separate title and data: "BALANCE" "123" OR "ID23" "3" | each one in separate variable.

You can extract the value using a regular expression for example, something like this
var response:String = "BALANCE:123.00"
var pattern:RegExp = new RegExp("BALANCE:([0-9.-]+)");
var data:Object = pattern.exec(response);
if (data != null && data[1] != null) {
var value:Number = parseFloat(data[1]);
trace(value);
}
The one i provided is fairly simple, to extract data from a known data format but, as long as there's a pattern in the string, you can extract the pieces of information you need.
Check out the guide on how to use RegExp in actionscript

Related

New array for music symbols

I have background musics from the library, any ideas how to solve this code by clicking the button to change it?
var BeachBall: CrashBash_BeachBall = new CrashBash_BeachBall();
var BrickDive: LEGOIsland2_BrickDive = new LEGOIsland2_BrickDive();
var BloocheepOcean: MarioHoops_BloocheepOcean = new MarioHoops_BloocheepOcean();
var Underwater: MarioTeachesTyping2_Underwater = new MarioTeachesTyping2_Underwater();
var UnderPressure: CrashBandicootNST_UnderPressure = new CrashBandicootNST_UnderPressure();
var CalmWaters: DireDireDocks_CalmWaters = new DireDireDocks_CalmWaters();
var Level1: TreasureCove_Level1 = new TreasureCove_Level1();
var Level2: TreasureCove_Level2 = new TreasureCove_Level2();
var Level3: TreasureCove_Level3 = new TreasureCove_Level3();
var music: Array = new Array(CalmWaters, BloocheepOcean, UnderPressure, Underwater, BeachBall, BrickDive, Level1, Level2, Level3);
// Changing the Background Music
music_btn.addEventListener(MouseEvent.CLICK, on_pressMusic);
music[Math.floor(Math.random()*music.length)].play();
if(!sound)
{
sound_channel = CalmWaters.play(0, int.MAX_VALUE);
sound_channel.soundTransform = new SoundTransform(0.4);
}
function on_pressMusic(event: MouseEvent): void
{
/*
var random: int = int(Math.random() * sounds[0].length);
play_music(sounds[0][random]);
var sMusic:Button = new Button();
sMusic.play();
*/
if (is_Playing == true) //# if music is already playing
{
music_player.stop();
}
musicNum = Math.floor(Math.random() * (musicList.length-1));
music_object = new (musicList[musicNum]);
audioTime = 0; //# seconds to start from within track
music_player = music_object.play(audioTime);
is_Playing = true;
}
Error:
TypeError: Error #1007: Instantiation attempted on a non-constructor.
at BlowfishPong_fla::MainTimeline/on_pressMusic()[BlowfishPong_fla.MainTimeline::frame27:205]
All of the codes are updated. any ideas how to solve and fix this for their future coding.
Try something like this:
var BeachBall: CrashBash_BeachBall = new CrashBash_BeachBall();
var BrickDive: LEGOIsland2_BrickDive = new LEGOIsland2_BrickDive();
var BloocheepOcean: MarioHoops_BloocheepOcean = new MarioHoops_BloocheepOcean();
var CalmWaters: DireDireDocks_CalmWaters = new DireDireDocks_CalmWaters();
var Level1: TreasureCove_Level1 = new TreasureCove_Level1();
var Level2: TreasureCove_Level2 = new TreasureCove_Level2();
var Level3: TreasureCove_Level3 = new TreasureCove_Level3();
var Underwater: MarioTeachesTyping2_Underwater = new MarioTeachesTyping2_Underwater();
var UnderPressure: CrashBandicootNST_UnderPressure = new CrashBandicootNST_UnderPressure();
var myNum :uint = 0;
var audioTime :uint = 0;
var music_object :Sound;
var music_player :SoundChannel = new SoundChannel();
var is_Playing :Boolean = false;
var music_list :Array = new Array();
music_list = [ BeachBall, BrickDive, BloocheepOcean, CalmWaters,
Level1, Level2, Level3, Underwater, UnderPressure
];
//# Changing the Background Music
music_btn.addEventListener(MouseEvent.CLICK, on_pressMusic);
function on_pressMusic (event:MouseEvent) : void
{
if ( is_Playing == true ) //# if music is already playing
{ music_player.stop(); }
myNum = Math.floor( Math.random() * (music_list.length-1) );
music_object = new ( music_list[ myNum ] );
audioTime = 0; //# seconds to start from within track
music_player = music_object.play( audioTime );
is_Playing = true;
}

Match two strings from a text file and user input? (AS3)

I was able to load a text file in a Flash file, but I am unable to match two strings from a text file and the user input.
The purpose of this AS3 code: to match the text file and user input, and if it matches, the score will increase by 1. Else, the score will increase by 0.
Here is my code:
var uScore :Number = 0;
stop();
var textLoader:URLLoader = new URLLoader();
var textURLRequest:URLRequest = new URLRequest("q1.txt");
textLoader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void
{
var textData:String = new String(textLoader.data);
dy1.text = textData;
}
textLoader.load(textURLRequest);
function goURL(event:MouseEvent):void {
var textLoader2:URLLoader = new URLLoader();
var textURLRequest2:URLRequest = new URLRequest("answer1.txt");
var textData2:String = new String(textLoader2.data);
var name1 = trace(textData2);
textLoader2.load(textURLRequest2);
var myURL = url1.text;
if(myURL == name1){
uScore += 1;
uScoreURL.text = uScore+"";
nextFrame();
}
else{
uScore+=0;
uScoreURL.text = uScore+"";
nextFrame();
}
}
trace(uScore);
You code has a strange assignment:
var name1 = trace(textData2);
replace it with
var name1 =textData2;
it should work then if there isn't a bug in some other place.
And you don't need to uScore+=0;. Just delete it.
I checked out your code, you were doing a few things out of order - here is the revised code that should get you where you need to be
var uScore :Number = 0;
stop();
var textLoader:URLLoader = new URLLoader();
var textURLRequest:URLRequest = new URLRequest("q1.txt");
textLoader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void
{
var textData:String = new String(textLoader.data);
dy1.text = textData;
}
textLoader.load(textURLRequest);
btn.addEventListener(MouseEvent.CLICK,getNumber);
var textLoader2:URLLoader = new URLLoader();
textLoader2.addEventListener(Event.COMPLETE, completeHandler2);
function completeHandler2(event:Event):void
{
var textData2:String = new String(textLoader2.data);
var name1 = textData2;
trace(name1);
var myURL = url1.text;
if(myURL == name1){
uScore += 1;
uScoreURL.text = uScore+"";
nextFrame();
}
else{
uScore+=0;
uScoreURL.text = uScore+"";
nextFrame();
}
}
function getNumber(event:MouseEvent){
var textURLRequest2:URLRequest = new URLRequest("answer1.txt");
textLoader2.load(textURLRequest2);
}
trace(uScore);
The only thing that I really added that you didn't have is a button with the variable name btn to check the answer - you can rework that to however you want to check for the answer.

Dealing with Twitter API 1.1 update_with_media ActionScript 3

i'm using as3 for my current project, login, post status to twitter is already done.. but i have problem with update_with_media. Here's the flow of my program. On other screen call it CaptureWebcam, user can capture pic from webcam but can't save it to user computer. And if user open share to twitter screen, there's popup to login and image from CaptureWebcam screen passed to twitter screen, and ready to upload and it failed to post... i don't know whats wrong with my code
here's my code, i'm using iotashan library
private function uploadImage(Image()):void {
var myEncoder:JPGEncoder = new JPGEncoder(80);
var urlLoader:URLLoader = new URLLoader();
var urlRequest:URLRequest;
var multipartLoader:MultipartURLLoader = new MultipartURLLoader();
var urlHeader:URLRequestHeader = new URLRequestHeader();
var oAuth:OAuthRequest;
var consumer:OAuthConsumer;
var twitterRequestUrl:String;
var headerValue:String = "";
var auth_header:URLRequestHeader;
var param:Object;
var vid:Video;
//var bmp:Bitmap = new Bitmap();
var bitmapData:BitmapData = new BitmapData(CaptureWebcam.vid.width, CaptureWebcam.vid.height, true, 0xFFFFFF);
//var byteArray:ByteArray = myEncoder.encode(new Bitmap(new Turtle()).bitmapData);
var byteArray:ByteArray = myEncoder.encode(bitmapData);
var drawRect:Rectangle = new Rectangle(0,0,image.width, image.height);
bitmapData.draw(image, new Matrix(), null, null, drawRect, true);
trace("upload test");
//header create
twitterRequestUrl = "https://api.twitter.com/1.1/statuses/update_with_media.json";
consumer = new OAuthConsumer(consumerKey, consumerSecret);
oAuth = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_POST, twitterRequestUrl, null, consumer, null);
urlRequest = new URLRequest(oAuth.buildRequest(new OAuthSignatureMethod_HMAC_SHA1()));
//
/*
urlRequest = twitterRequestUrl;
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData(file, byteArray);
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
urlLoader.dataFormat = URLLoaderDataFormat.BINARY
urlLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, onStatusDelivered);
urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatusChanged);
urlLoader.addEventListener(Event.COMPLETE, handleUploadComplete);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
urlLoader.load(urlRequest);
*/
/*
multipartLoader.addEventListener(Event.COMPLETE, handleUploadComplete);
multipartLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
multipartLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSequrityError);
multipartLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, onStatusDelivered);
*/
/*
headerValue = createHeaderValue(oAuth);
auth_header = new URLRequestHeader("Authorization", headerValue);
multipartLoader.requestHeaders.push(auth_header);
multipartLoader.addVariable("status" , "test");
multipartLoader.addFile(byteArray, 'image.jpg', 'media[]');
multipartLoader.load("https://api.twitter.com/1.1/statuses/update_with_media.json");
*/
var signedData:String = oauth.getSignedRequest( URLRequestMethod.POST, "https://upload.twitter.com/1/statuses/update_with_media.json", null );
var authHeaderValue:String = createAuthorizationHeader( new URLVariables( signedData ) );
// create multipart loader
var multipartLoader : MultipartURLLoader = new MultipartURLLoader();
multipartLoader.addEventListener( Event.COMPLETE, handleUploadComplete );
multipartLoader.addEventListener( IOErrorEvent.IO_ERROR, onError );
multipartLoader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onError );
// add headers
var auth_header : URLRequestHeader = new URLRequestHeader( "Authorization", authHeaderValue );
multipartLoader.requestHeaders.push( auth_header );
// add requeried data
multipartLoader.addVariable( "status" , twitter_msg );
multipartLoader.addFile( byteArray, 'image.jpg', 'media[]');
// load
multipartLoader.load( "https://upload.twitter.com/1/statuses/update_with_media.json" );
}
private function createAuthorizationHeader( _requestParams : Object, headerRealm : String = "" ) : String
{
var data:String = "";
data += "OAuth "
if ( headerRealm.length > 0)
data += "realm=\"" + headerRealm + "\", ";
for (var param : Object in _requestParams ) {
// if this is an oauth param, include it
if ( param.toString().indexOf("oauth") == 0){
data += param + "=\"" + encodeURIComponent( _requestParams[param]) + "\", ";
}
}
return data.substr( 0, data.length - 2);
}

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.

Sending textarea text to datagrid as object

I would like a text area that holds multiple strings to send its values to an array and the array to convert the string to an object. The objects then populate a datagrid. I can't really figure out where to go from here:
var arrayString:String = myTextArea.text;
var newArray:Array = arrayString.split(",");
var n:int=newArray.length;
while (n--)
{
newArray[n]=Number(newArray[n])
var obj:Object = new Object();
obj.label = newArray[n];
this.myDataGrid.addItem(obj );
}
var arrayString:String = myTextArea.text;
var newArray:Array = arrayString.split(",");
var n:int=newArray.length;
var dataProvider:ArrayCollection = new ArrayCollection;
while (n--)
{
newArray[n]=Number(newArray[n])
var obj:Object = { label: newArray[n] };
dataProvider.addItem(obj);
}
this.myDataGrid.dataProvider = dataProvider;