Can't get a working progress bar for file download AS3 - actionscript-3

I'm currently enrolled in an ActionScript course, and cannot seem to get my progress bar to work correctly. We were tasked with creating a simple image loader application, which would access externally hosted images (through use of a PHP proxy script), and then spit the image onto the user's screen (with a progress event and progress bar to track the image's download progress).
However, when I run it, I get these mysterious black graphical glitches everywhere, as well as a non-functioning progress bar. In some browsers I get the following error: "ArgumentError: Error #2109: Frame label NaN not found in scene NaN. at flash.display.MovieClip/gotoAndStop() at Document/imageLoadProgress().
Here is my code - I cant for the life of me figure out what is wrong. I figure it has something to do with the imageLoadProgress() function, or my progress bar (which is just a simple 100-frame movie clip with a motion tween and a "stop()" command at the beginning).
public function loadImage()
{
var imageURL:String = imageArray[currentImageIndex];
if(loaderInfo.url.substr(0,4) == "http")
{
trace("we're online");
//use the proxy script
//escape() will replace spaces in file names with %20
imageURL = "./image_proxy.php?filename=" + escape(imageArray[currentImageIndex]);
}
var imageRequest:URLRequest = new URLRequest(imageURL);
this.imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.imageIOError);
this.imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, this.imageLoadProgress);
this.imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.imageLoadComplete);
this.imageLoader.load(imageRequest);
//end loadImage
}
public function imageIOError(e:Event)
{
trace("ImageIOError called. Error=" + e);
//end imageIOError
}
public function imageLoadProgress(e:ProgressEvent)
{
var percentLoaded:Number = e.bytesLoaded/e.bytesTotal;
percentLoaded = Math.round(percentLoaded * 100);
//this.progress_mc.scaleY = percentLoaded;
if (percentLoaded < 1)
{
this.progressBar.gotoAndStop(1);
}
else
{
this.progressBar.gotoAndStop(percentLoaded);
}
//end imageLoadProgress
}

Your loader script seems absolutely fine to me, except for a tiny flaw:
The only way the NaN(== not a Number) in your error message makes sense to me is if your ProgressEvent's bytesTotal property equals 0 - because division by zero doesn't produce valid results, as we all know.
I can't say for sure why this happens, not knowing any of your server-side code, but I assume it would occur if your PHP proxy script does not set the Content-Length HTTP response header correctly. If you were loading an actual image file, the web server would automatically set the header for you - in the case of your proxy script, it seems you have to take care of it yourself.
Anyway, you can make your loader script more error-proof by testing for NaN, and making sure the frame you jump to is never greater than 100:
var frame:int = isNaN (percentLoaded) || percentLoaded < 1 ? 1 :
percentLoaded > 100 ? 100 : percentLoaded;
progressBar.gotoAndStop(frame);
(I chose shorthand notation, but this is essentially the same as writing two if statements and an else).

Related

How do you share a variable between scripts using the MovieClip variable?

I'm currently trying to code an interactive timeline for my Uni project (keep in mind im a new coder) and we go over basic actionscript stuff. I was taught to communicate between scripts using a movieclip variable and declaring this.parent.
I have 3 scripts, one that controls the button that is used to move forward in the timeline, one is main, and the other controls the text box which displays the timeline. I placed a number variable in main, initialised at 0(timeCount). In the button script, i have it linked to main using refToMain, my movieclip variable. Within the button script, if the user clicks on the button, it rises the number variable from main using refToMain(refToMain.timeCount). It was my ambition to have the text box script track the number and each number has a different bit of the timeline on. However, when I trace timeCount in the button script, the number seems fine and raises accordingly, however it doesnt change the number in any other script. How can I fix this using basic as3 code?
In Main:
var timeCount:Number = 0;
In Button:
public function mDown (mDown:MouseEvent){
refToMain.timeCount += 1;
if(refToMain.timeCount >= 10){
refToMain.timeCount = 10;
}
trace(refToMain.timeCount);
In timeline:
if(refToMain.timeCount == 0){
timelineText.text = "welcome"
}
if(refToMain.timeCount == 1){
timelineText.text = "hello"
}
Are you expecting the code in your timeline to run continuously instead of just once? A frame script will only run once each time the timeline reaches that frame. And if you only have one frame, the timeline won't advance at all. If that's the case, a simple fix would be to add another frame to your timeline with F5, and then your timeline will alternate between your two frames forever so that your script on frame 1 will execute every other frame.
A better option would be to call the script that updates the timeline text directly every time the button is clicked. So you would move the code from your timeline script to your button script like this:
public function mDown (mDown:MouseEvent) {
refToMain.timeCount += 1;
if(refToMain.timeCount >= 10) {
refToMain.timeCount = 10;
}
trace(refToMain.timeCount);
if(refToMain.timeCount == 0) {
MovieClip(root).timelineText.text = "welcome";
}
if(refToMain.timeCount == 1) {
MovieClip(root).timelineText.text = "hello";
}
}
There are several ways and approaches to access objects and variables across your application.
1) Traversing. The (probably) older and the most straightforward one is fully understanding and controlling the display list tree. If you understand where your current script is and where your target script is, you just traverse this tree with root to go straight to the top, parent to go level up and getChildByName or [] or dot notation to go level down.
Pros: it's simple. Contras: The weak point of this approach is its inflexibility. Once you change the structure of display list tree, the access would presumably be broken. Also, this way you might not be able to access things that are not on the display list. Also, there are cases the dot notation would not work, and there are cases getChildByName would not work. Not that simple, after all.
2) Bubbling events. These are events that bubble from the depths of display list to the root. Mouse events are bubbling: you can catch it anywhere from the deepest object that had some mouse event then all its parents right up to the stage. You can read about them here. So, you can send bubbles from whatever depth you want then intercept them at the any parent of the event target:
// *** TextEvent.as class file *** //
package
{
import flash.events.Event;
public class TextEvent extends Event
{
static public const TEXT_EVENT:String = "text_event";
public var text:String;
// Although it is not a very good practice to leave the basic Event
// parameters out of it, but it will do for this example.
public function TextEvent(value:String)
{
// Set type = "text_event" and bubbles = true.
super(TEXT_EVENT, true);
text = value;
}
}
}
// *** Button script *** //
import TextEvent;
// Dispatch the event.
dispatchEvent(new TextEvent("welcome"));
// *** Main timeline *** //
import TextEvent;
// Subscribe to catch events.
addEventListener(TextEvent.TEXT_EVENT, onText);
function onText(e:TextEvent):void
{
// Extract the passed text value.
timelineText.text = e.text;
}
Pros: it is good in an app architecture terms. Contras: you cannot catch the bubbling event at the point that is not parent of event source.
3) Static class members. Or singleton pattern, its basically the same. You can devise a class that shares certain values and references over the whole application:
// *** SharedData.as class file *** //
package
{
import flash.display.MovieClip;
public class SharedData
{
static public var MainTimeline:MovieClip;
}
}
// *** Main timeline *** //
import SharedData;
// Make root accessible from anywhere.
SharedData.MainTimeline = this;
// *** Button script *** //
import SharedData;
// You can access main timeline via shared reference.
SharedData.MainTimeline.timelineText.text = "welcome";
Pros: you are not limited by display list structure any more, you can also share non-visual instances this way, anything. Contras: careful with timelines, they tend to destroy and create timeline instances as playhead moves, so it is not impossible to end up with a reference to a removed object while timeline holds a new instance that is no longer shared.

Actionscript(AIR) Cant return FB access_token from HTMLLoader

Im simply trying to get my users access token from FB using HTMLLoader. When i trace the output from the location change event all i get are Google/FB urls, none of which have the token.
Here is my code:
var loader:HTMLLoader;
function onChange(e:Event):void {
if(loader.location.indexOf("#") != -1) {
trace("Found token");
}else {
trace(loader.location);
}
}
function connectFb() {
loader = new HTMLLoader();
loader.addEventListener(Event.LOCATION_CHANGE, onChange);
loader.width = 640;
loader.height = 480;
loader.load(new URLRequest("https://graph.facebook.com/oauth/authorize?
client_id=1234567890123456&redirect_uri=http://google.com&type=user_agent"));
}
My Codes output:
https://graph.facebook.com/oauth/authorize?client_id=164534120383085&redirect_uri=http://google.com&type=user_agent
http://www.google.com/
I tried every tutorial on the net and even bought a book on AS3 facebook dev & still cant figure this out; Any help would be VERY appreciated since this is a fairly important project to me
From what I understand, you're trying to retrieve an oauth access token from the facebook API, right? That's what you're expecting to get back from that URL? Correct me if I'm wrong, but HTMLLoader is for (unsurprisingly) loading HTML content. If you're expecting HTML content (ie, an 'authorize' page from FB), then you need to add the HTMLLoader to the display list with:
addChild(loader); // where 'loader' is an instance of HTMLLoader
On the other hand, if you were expecting just the token (and not HTML content), then you should be using URLLoader, and not HTMLLoader.

From synchronous flow to asynchronous flow dilemma

As a PHP programmer I'm very habituated to the fact that the program flow goes line by line, if I call function1() that have to return some value I know the program wont continue until that function makes a return.
Now, im developing a AS3 app using AIR, I need to download some images if some conditions are met, don't know how many, so im using a For like this:
for (var w:int=0; w < newData_array[2]['content'].length; w++ ) {
for (var j:int=0; j < oldData_array[2]['content'].length; j++ ) {
if((oldData_array[2]['content'][j]['id'] == newData_array[2]['content'][w]['id']) && (oldData_array[2]['content'][j]['last_mod'] != newData_array[2]['content'][w]['last_mod'])){
//need to download a image...
}
}
}
As you can see im just comparing each element from each array (newData_array and oldData_array). If the condition met, I need to download something, for that I'm using URLloader and as you know this function is asynchronous, adding a listener, an event will be triggered when the download is complete, the problem is very clear, since the urlloader wont stop the for cycle (like I would expect on a PHP alike language) I'm just going to download a bunch of images at the same time creating a disaster because I wont know when to save. So I need to use by any mean the listener, but since I'm not very habituated to this kind of procedures I'm pretty munch stuck.
Im not interested on the save to disk routines, that part is pretty much done, I just want to understand how I should structure this algorithm to make this work.
This annoyed me too, but one has to realize that you can't do something to something that doesn't exist in memory yet, and these loading operations can take quite some time. Being a single-threaded stack, Flash Player's load operations would require that the entire interface to freeze during the load (if restricted to the loop).
Obviously there's data available to the loop that dictates what you do with the image. The solution I've been using is create a custom load function that starts the load, and returns a proxy image . Your loop gets a container back and you can freely place your image where you want.
In the meantime, your loader listener has kept track of the active images loading, and their associated proxies. When loaded, swap the image in.
Your loop would look something like this...
for (var w:int in newData_array[2]['content']) {
for (var j:int in oldData_array[2]['content']) {
if ((oldData_array[2]['content'][j]['id'] == newData_array[2]['content'][w]['id']) && (oldData_array[2]['content'][j]['last_mod'] != newData_array[2]['content'][w]['last_mod'])){
var proxy:MovieClip = loadImage("image/path.jpg");
// Do stuff to proxy.
}
}
}
And your function + listener would look something like this...
var proxies:Object = {};
function loadImage(path:String):MovieClip {
// load Image
var proxy:MovieClip = new MovieClip();
proxies.path = proxy;
// Load Image
}
function imageLoaded(e:Event):void {
// Once loaded, use the filename as the proxy object's key to find the MovieClip to attach the image.
proxies[e.data.loaderInfo.filename].addChild(e.data);
}
This is just off the top of my head, so you'll need to find the actual variable names, but I hope that makes sense.
I am not really sure if I understood your problem but it seems to me that you simply add the according listener in your inner loop.
//take care this is pseudocode
var parent = ... // some stage object
for (var w:int=0; w < size1; w++ ) {
for (var j:int=0; j < size2; j++ ) {
if(some_condition){
request = new URLRequest(getNextImagePath();
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.load(request);
}
}
}
function onComplete(event:Event) {
parent.addChild(createImageFromData(this.data));
}
I solved the problem using an third party library that pretty munch handles this problem.
https://github.com/arthur-debert/BulkLoader

Refreshing picture in drawingPanel extends JPanel 2

i apologise for having posted a thread quite similar to this one. but still i am having some problems. thread can be seen here
i am applying a backfround to a jpanel. i need to have a loading gifthat changes later on for a ok or error image.
i load at the beginning a trasparent picture. it get replaced as soon as an action listener starts by the loading one and in the end of the code executed in the listener i change the figure with ok/error. the transparent, the ok and the error one get loaded perfectly but i did not manage to see the loading one.
here is my listener code:
void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {
// load loading icon
Image img = new ImageIcon(iconPath+"loading.gif").getImage();
this.iconPanel.replaceImage(img);
this.iconPanel.updateUI();
this.iconPanel.revalidate();
this.iconPanel.repaint();
// clear table contents
designValue.clear();
deployValue.clear();
// Fill class
diagnosticGenerator diagnostic = new diagnosticGenerator();
Vector<Integer> indexes;
// if modeCombo.getSelectedIndex() == 0 i show only data regarding the current user
if (modeCombo.getSelectedIndex() == 0) {
// receive Design Table
designValue.addAll(diagnostic.getDesignContents());
// receive Deploy Table
deployValue.addAll(diagnostic.getDeployContents());
// receive indexes of out-dated deploy
indexes = new Vector<Integer>(diagnostic.getOutdatedDeployIndexes());
}
// otherwise i show data of all the users
else {
// receive Design Table
designValue.addAll(diagnostic.getDesignContents_allUsers());
// receive Deploy Table
deployValue.addAll(diagnostic.getDeployContents_allUsers());
// receive indexes of out-dated deploy
indexes = new Vector<Integer>(diagnostic.getOutdatedDeployIndexes_allUsers());
}
// set default color to green
deployTable.resetColor(Color.white);
// set red background to the
for (Integer x : indexes)
deployTable.setRowColor(x, Color.red);
deployTable.repaint();
designTable.revalidate();
deployTable.revalidate();
//update refreshLabel with the new date
Date date = new Date();
refreshLabel.setText(date.toString());
//replace icon with different mark depending on the fact if we found an error or not
if(indexes.isEmpty())
img = new ImageIcon(iconPath+"ok.png").getImage();
else
img = new ImageIcon(iconPath+"error.png").getImage();
this.iconPanel.replaceImage(img);
this.iconPanel.repaint();
}
i think it's a matter of asyncronous messages because if i call a wait just after
this.iconPanel.repaint();
i can see the loading gif. but my code gets stuck there.
So i think i shoud find a way to force at that point to execute all the command in queue but i have no idea how to do it.
does anyone had a similar problem with swing?
Use a blocking method such as ImageIO.read(File/URL/InputStream) to get the Image. ImageIO has been introduced into the J2SE 'recently'.

calling function in a runtime loaded swf

Using AS3 / Flash CS4
Alright thanks to everyone who is reading this. My problem specifically I am designing a user interface with controls on it. 5 buttons rotate left, rotate right, zoom in, zoom out, and auto rotate. The interface in itself works fine, I can trace out button clicks, toggle the auto rotate button etc...
My program reads an xml file. Loads some images, fills an array with links for each image, and when the image is clicked a loader loads a swf from a URL and displays it on screen. No problem.
Now I originally had the zoom controls user interface in the runtime_loaded.fla library, and the mouse listeners in the same linked document class. The interface works with the movieClip in runtime_loaded.swf when it is in the same code.
Now to practice good coding, I decided to remove the UI from the runtime_loaded.fla and add it to the Main.fla. This is essential because the main is going to handle possible 100's of images/objects that each have their own unique swf to link too. If I decide to change out the look of the interface but leave the function calls the same, I could essentially put in as many as I want into the main.fla instead of the runtime_loaded.fla which I would have to do for every single object.
THE FILE STRUCTURE
Main.fla <- interface in the library. 5 mouse event functions. Inside each function calls
a property of loaded_swf (loaded_swf.rotateLeft, loaded_swf.rotateRight) etc...
Runtime_loaded.fla <- links specificObject.as in properties (AS3/CS4)
specificObject.as <- has 5 public static functions{ rotateRight, rotateLeft, zoomIn, zoomOut, toggleAutoRotate }
THE CODE
//showFlashBox
function showFlashBox(temp_string:String):void {
if(!flash_box_on){
var temp_top:uint = numChildren;
addChildAt(FlashBoxContainer,temp_top);
newXButton.addEventListener(MouseEvent.CLICK, flashBoxXClick);
1. addChild(new_loader);
2. var url:URLRequest = new URLRequest(temp_string);
new_loader.x = 0;
new_loader.y = 0;
new_loader.load(url);
3. new_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, gotSwf);
flash_box_on = true;
}
}
function gotSwf(e:Event){
4. //loaded_swf = e.target.content;
trace(e.target.content);
5. new_zoom_controls.button_minus.addEventListener(MouseEvent.CLICK, zoomOutFunction);
new_zoom_controls.button_plus.addEventListener(MouseEvent.CLICK, zoomInFunction);
new_zoom_controls.button_left.addEventListener(MouseEvent.CLICK, rotateLeftFunction);
new_zoom_controls.button_right.addEventListener(MouseEvent.CLICK, rotateRightFunction);
new_zoom_controls.button_rotate.addEventListener(MouseEvent.CLICK, toggleRotateFunction);
function rotateRightFunction(e:MouseEvent){
6. //loaded_swf.rotateRight();
}
function rotateLeftFunction(e:MouseEvent){
//loaded_swf.rotateLeft();
}
function zoomInFunction(e:MouseEvent){
//loaded_swf.zoomIn();
}
function zoomOutFunction(e:MouseEvent){
//loaded_swf.zoomOut();
}
function toggleRotateFunction(e:MouseEvent){
//loaded_swf.toggleAutoRotate();
if(new_zoom_controls.button_rotate.currentFrame == 1){
new_zoom_controls.button_rotate.gotoAndStop(2);
}
else new_zoom_controls.button_rotate.gotoAndStop(1);
}
new_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, gotSwf);
}
If you follow steps 1-6 you see my steps of loading the .swf, mouse event listeners and click handlers, then the object call of the var loaded_swf:Object;
public static function rotateLeft():void
{
object.yaw(animation_turning_speed);
}
public static function rotateRight():void
{
object.yaw(-animation_turning_speed);
}
if I run the main.fla and try to click the buttons. This happens.
ReferenceError: Error #1069: Property rotateRight not found on
ThreedsKU39web and there is no default value. at MethodInfo-82()
ReferenceError: Error #1069: Property rotateLeft not found on
ThreedsKU39web and there is no default value. at MethodInfo-83()
I actually stumbled upon the answer before I finished submitting this as I went through the code to copy it. But after spending a few hours of frustrating moments on this last night, I will post it to ensure the next guy doesn't meet the same demise.
The answer was in the function of the runtime-loaded swf class.
public static function rotateRight():void
{
object.yaw(-animation_turning_speed);
}
It turns out it only needs to be public function instead of public static.
Mainly human error as after the file was working, I attempted to copy the code over to all my other object files, and somehow static got back in there and messed it up. So for future reference when loading in the external swf, public function should do the trick. *Note that many of my variables were returning errors until being declared as public static though.