AS3 time that needs to pause - actionscript

I'm working on a mobile game and need the game clock to pause when the game loses focus, for example when call comes in. I have everything working except that when the game gains focus again the time adjusts to as if it had been running the whole time. If someone is on a 3 minute call when they get back they should find the game time where it was.
Here is my code:
public function showTime(event:Event){
gameTime = getTimer()-gameStartTime;
timeDisplay.text = "Time: "+clockTime(gameTime);
}
public function clockTime(ms:int) {
var seconds:int = Math.floor(ms/1000);
var minutes:int = Math.floor(seconds/60);
seconds -= minutes*60;
var timeString:String = minutes+":"+String(seconds+100).substr(1,2);
return timeString;
}
public function onActivate(event:Event):void {
addEventListener(Event.ENTER_FRAME, showTime);
}
public function onDeactivate(event:Event):void {
removeEventListener(Event.ENTER_FRAME, showTime);
}
I've been Googling this for two days and am stuck. Could someone please point me in the right direction? Some sample code would be a benefit too since I'm pretty new to AS3. Thanks!
Rich

You can check out this Stopwatch tutorial that I wrote a while back:
http://www.popamihai.com/2010/10/flex/using-the-timer-class-in-flex-to-display-a-simple-stopwatch/
It is written with Flex Builder 3 but you could easily copy/paste the code. Example with view source enabled is also included
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
backgroundColor="white" viewSourceURL="srcview/index.html" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.events.TimerEvent;
private const TIMER_INTERVAL:int = 50;
private var timerAtStart:Number = 0;
private var timerAtPause:Number = 0;
private var t:Timer;
private var d:Date;
[Bindable] private var sec:int = 0;
[Bindable] private var min:int = 0;
[Bindable] private var mls:int = 0;
private function init():void {
t = new Timer(TIMER_INTERVAL);
t.addEventListener( TimerEvent.TIMER, updateTimer );
}
private function updateTimer( evt:TimerEvent ):void{
d = new Date( getTimer() - timerAtStart + timerAtPause);
min = d.minutes;
sec = d.seconds;
mls = d.milliseconds;
}
private function startPauseTimer( event:MouseEvent ):void{
if ( event.target.label == "start" ) {
event.target.label = "pause";
timerAtStart = getTimer();
t.start();
} else {
event.target.label = "start";
timerAtPause = min * 60000 + sec * 1000 + mls;
t.stop();
}
}
]]>
</mx:Script>
<mx:Label text="{min + ' : ' + sec + ' : ' + mls}" fontSize="16" fontWeight="bold"/>
<mx:HBox>
<mx:Button label="start" click="startPauseTimer( event )"/>
</mx:HBox>
</mx:Application>

You're calculating your time based on the current time - gameStartTime. You either need to take the delay into account (calculate the total time stopped by using getTimer() in the onActivate() and onDeactivate() functions, then add that difference to gameStartTime), or if you don't want to change gameStartTime, then you calcuate your time based on delta time. Something like:
private var m_prevTime:int = 0;
public function startGame():void
{
// set the prevTime only when you start the game, otherwise you'll
// take into account all the time for flash to get going, your init,
// opening screens etc
this.m_prevTime = getTimer();
}
public function showTime(event:Event)
{
// get the difference in time
var currTime:int = getTimer();
gameTime += currTime - this.m_prevTime // currTime - prevTime = delta time
this.m_prevTime = currTime; // hold the current time
// display it
timeDisplay.text = "Time: "+clockTime(gameTime);
}
public function onActivate(event:Event):void
{
// we're reactivating, so make sure prev time is updated
this.m_prevTime = getTimer();
addEventListener(Event.ENTER_FRAME, showTime);
}
You'll miss out on a frame's time when coming back from the update, but it's not noticable (or you can subtract a frame's time in the onActivate() function)

Instead of using getTimer(), you should create a timer object and add an event listener to "tick" to update the clock. You can even set it to tick once per second so you don't have to convert the MS.
public function onActivate(event:Event):void {
myTimer.start();
}
public function onDeactivate(event:Event):void {
myTimer.stop();
}
See the timer reference: http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/utils/Timer.html

Related

Parsing error Unity 3D

I keep on getting this error code (UCE0001: ';' expected. Insert a semicolon at the end.), and I really just dont get why. Please help, what am I overlooking:
#pragma strict
private var vibrateTimer : float = 0.0;
function Update()
{
if (action);
{
vibrate on();
vibrateTimer = 0.25;
}
if (vibrateTimer > 0.0);
{
vibrateTimer -= Time.deltaTime;
if (vibrateTimer <= 0.0);
{
vibrate off();
}
}
}
Is this Javascript or C# or UnityScript? The using UnityEngine; says C#, the function says Javascript, the vibrate on says neither. Please clarify.
Starting from
private var vibrateTimer : float = 0.0 ();
{
//....
}
why are you wrapping the whole code in { }?
Also,
vibrate on
vibrateTimer = 0.25f;
(the first line) is not valid C# code. Also the variable declaratoin
private var vibrateTimer : float = 0.0 ();
with the () at the end seems wrong to me. But the wrapping the whole code in {} might be your first error source.

How to wait for 3 seconds in ActionScript 2 or 3?

Is there any way to implement waiting for, say, 3 seconds in ActionScript, but to stay within same function? I have looked setInterval, setTimeOut and similar functions, but what I really need is this:
public function foo(param1, param2, param3) {
//do something here
//wait for 3 seconds
//3 seconds have passed, now do something more
}
In case you wonder why I need this - it is a legal requirement, and no, I can't change it.
Use the Timer to call a function after 3 seconds.
var timer:Timer = new Timer(3000);
timer.addEventListener(TimerEvent.TIMER, callback); // will call callback()
timer.start();
To do this properly, you should create the timer as an instance variable so you can remove the listener and the timer instance when the function is called, to avoid leaks.
class Test {
private var timer:Timer = new Timer(3000);
public function foo(param1:int, param2:int, param3:int):void {
// do something here
timer.addEventListener(TimerEvent.TIMER, fooPartTwo);
timer.start();
}
private function fooPartTwo(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, fooPartTwo);
timer = null;
// 3 seconds have passed, now do something more
}
}
You could also use another function inside your foo function and retain scope, so you don't need to pass variables around.
function foo(param1:int, param2:int, param3:int):void {
var x:int = 2; // you can use variables as you would normally
// do something here
var timer:Timer = new Timer(3000);
var afterWaiting:Function = function(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, afterWaiting);
timer = null;
// 3 seconds have passed, now do something more
// the scope is retained and you can still refer to the variables you
// used earlier
x += 2;
}
timer.addEventListener(TimerEvent.TIMER, afterWaiting);
timer.start();
}
For AS3 use Radu's answer.
For AS2 use the setInterval function like so:
var timer = setInterval(function, 3000, param1, param2);
function (param1, param2) {
// your function here
clearInterval(timer);
}
You can also use delayedCall, from TweenMax. IMHO, it's the sharpest way to do that if you are familiar to TweenMax family.
TweenMax.delayedCall(1, myFunction, ["param1", 2]);
function myFunction(param1:String, param2:Number):void
{
trace("called myFunction and passed params: " + param1 + ", " + param2);
}
In your case, using a anonymous function:
public function foo(param1, param2, param3) {
//do something here
trace("I gonna wait 3 seconds");
TweenMax.delayedCall(3, function()
{
trace("3 seconds have passed");
});
}
why you are doing some confused ways instead of doing the right way?
there is a method named:"setTimeout()";
setTimeout(myFunction,3000);
myFunction is the function you want to call after the period.and 3000 is the period you want to wait(as miliseconds).
you don't need to set then clear interval, or make a timer with one repeat count or do sth else with more trouble☺.
There is no Sleep in ActionScript. But there are other ways to achieve the same thing without having all your code in a single function and wait within that function a specific amount of time.
You can easily have your code in two functions and call the 2nd one after a specific timeout you set in your 1st function.
THIS IS NOT WITHIN ONE FUNCTION - ANSWERS: "How to wait for X seconds in AS2 & 3"
...without using setInterval or clearInterval.
The answers posted above are much faster and easier to use. I posted this here, just in case...
Sometimes you may not be able to use set/clearInterval or other methods based on development restrictions. Here is a way to make a delay happen without using those methods.
AS2 - If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
I have an onEnterFrame countdown timer in here as well, (demos stopping/switching timers).
If you want the delay/glow to be longer - increase the glowGameTime number. Change the names to fit your own needs and/or apply the logic differently.
var startTime:Number = 0;
var currentTime:Number = 0;
var mainTime:Number = 5;//"game" time on enter frame
var glowStartTime:Number = 0;
var glowCurrentTime:Number = 0;
var glowGameTime:Number = 1.8;//"delayed" time on press
btnGlowTest._visible = false;
this.onEnterFrame = TimerFunction;
startTime = getTimer();
function TimerFunction()
{
currentTime = getTimer();
var timeLeft:Number = mainTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up...3 bucks off");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
function glowTimerFunction()
{
glowCurrentTime = getTimer();
var glowTimeLeft:Number = glowGameTime - ((glowCurrentTime - glowStartTime)/1000);
glowTimeLeft = Math.floor(glowTimeLeft);
//trace("glowTimeleft = " + glowTimeLeft);
if(glowTimeLeft <= 0)
{
trace("TIME DELAY COMPLETE!");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
btnTest.onPress = function()
{
trace("onPress");
btnGlowTest._visible = true;
StopTime();
GlowTime();
}
function GlowTime()
{
trace("GlowTime Function");
this.onEnterFrame = glowTimerFunction;
glowStartTime = getTimer();
}
function StopTime()
{
trace(">>--StopTime--<<");
delete this.onEnterFrame;
}
AS3 - Below is the code from above setup to run in AS3. There are different ways to accomplish similar results, yet based on the project scope, these are the methods that were used in order to get things functioning properly.
If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
If you want the delay/glow to be longer - increase the GlowTimer:Timer number, (currently set to 950). Change the names to fit your own needs and/or apply the logic differently.
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
var startTime:Number = 0;
var currentTime:Number = 0;
var gameTime:Number = 4;//"game" time on enter frame
var GlowTimer:Timer = new Timer(950,0);//"delayed" time on press
btnGlowTest.visible = false;
GlowTimer.addEventListener(TimerEvent.TIMER, GlowTimeListener, false, 0, true);
btnTest.addEventListener(MouseEvent.MOUSE_DOWN, btnTestPressed, false, 0, true);
addEventListener(Event.ENTER_FRAME,TimerFunction, false, 0, true);
startTime = getTimer();
function TimerFunction(event:Event)
{
currentTime = getTimer();
var timeLeft:Number = gameTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up, 3 bucks off");
StopTime();
}
}
function GlowTimeListener (e:TimerEvent):void
{
trace("TIME DELAY COMPLETE!");
StopTime();
}
function btnTestPressed(e:MouseEvent)
{
trace("PRESSED");
removeEventListener(Event.ENTER_FRAME, TimerFunction);
btnGlowTest.visible = true;
GlowTimer.start();
}
function StopTime()
{
trace(">>--Stop Time--<<");
btnGlowTest.visible = false;//just for show
btnTest.visible = false;//just for show
GlowTimer.stop();
removeEventListener(TimerEvent.TIMER, GlowTimeListener);
removeEventListener(Event.ENTER_FRAME, TimerFunction);
}

iOS UIAutomation UIAElement.isVisible() throwing stale response?

I'm trying to use isVisible() within a loop to create a waitForElement type of a function for my iOS UIAutomation. When I try to use the following code, it fails while waiting for an element when a new screen pops up. The element is clearly there because if I do a delay(2) before tapping the element it works perfectly fine. How is everyone else accomplishing this, because I am at a loss...
Here's the waitForElement code that I am using:
function waitForElement(element, timeout, step) {
if (step == null) {
step = 0.5;
}
if (timeout == null) {
timeout = 10;
}
var stop = timeout/step;
for (var i = 0; i < stop; i++) {
if (element.isVisible()) {
return;
}
target.delay(step);
}
element.logElement();
throw("Not visible");
}
Here is a simple wait_for_element method that could be used:
this.wait_for_element = function(element, preDelay) {
if (!preDelay) {
target.delay(0);
}
else {
target.delay(preDelay);
}
var found = false;
var counter = 0;
while ((!found) && (counter < 60)) {
if (!element.isValid()) {
target.delay(0.5);
counter++;
}
else {
found = true;
target.delay(1);
}
}
}
I tend to stay away from my wait_for_element and look for any activityIndicator objects on screen. I use this method to actual wait for the page to load.
this.wait_for_page_load = function(preDelay) {
if (!preDelay) {
target.delay(0);
}
else {
target.delay(preDelay);
}
var done = false;
var counter = 0;
while ((!done) && (counter < 60)) {
var progressIndicator = UIATarget.localTarget().frontMostApp().windows()[0].activityIndicators()[0];
if (progressIndicator != "[object UIAElementNil]") {
target.delay(0.25);
counter++;
}
else {
done = true;
}
}
target.delay(0.25);
}
Here is a simple and better one using recursion. "return true" is not needed but incase u want it.
waitForElementToDismiss:function(elementToWait,waitTime){ //Using recursion to wait for an element. pass in 0 for waitTime
if(elementToWait && elementToWait.isValid() && elementToWait.isVisible() && (waitTime < 30)){
this.log("Waiting for element to invisible");
target.delay(1);
this.waitForElementToDismiss(elementToWait, waitTime++);
}
if(waitTime >=30){
fail("Possible login failed or too long to login. Took more than "+waitTime +" seconds")
}
return true;
}
Solution
I know this is an old question but here is my solution for a situation where I have to perform a repetitive task against a variable timed event. Since UIAutomation runs on javascript I use a recursive function with an empty while loop that checks the critical control state required before proceeding to the next screen. This way one never has to hard code a delay.
// Local target is the running simulator
var target = UIATarget.localTarget();
// Get the frontmost app running in the target
var app = target.frontMostApp();
// Grab the main window of the application
var window = app.mainWindow();
//Get the array of images on the screen
var allImages = window.images();
var helpButton = window.buttons()[0];
var nextButton = window.buttons()[2];
doSomething();
function doSomething ()
{
//only need to tap button for half the items in array
for (var i=0; i<(allImages.length/2); i++){
helpButton.tap();
}
//loop while my control is NOT enabled
while (!nextButton.isEnabled())
{
//wait
}
//proceed to next screen
nextButton.tap();
//go again
doSomething();
}

AIR application: Cannot access a property or method of a null object reference. No idea what's causing this

I'm using code for the open source MP3 player Howler and trying to port it to a Spark MobileApplication type. I'm getting a null pointer exception and I have no idea what's causing it. I've tried debugging extensively with breakpoints at what I think is causing the error, and set breakpoints in the untouched Howler project but all the variables in scope seem to be identical between my non-working project, and the Howler project. The only thing I can think of is that Howler uses MX components and I am using spark. I've pasted all my code below (which is very long) but I've bolded the lines that are throwing the error. The error occurs immediately after I choose a folder in the browse folder dialog.
<?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="Home"
xmlns:Comp="components.*" xmlns:display="flash.display.*">
<s:Button id="browse" x="546" y="43" label="Open Directory" click="browseForFolder()"/>
<s:DataGrid id="dgPlaylist" width="82" height="141" itemRenderer="components.DurationFormatter">
</s:DataGrid>
<s:Button id="btnForward" x="187" y="126" label="Forward"/>
<s:Button id="btnPause" x="90" y="39" label="Pause"/>
<s:Button id="btnBack" x="55" y="166" label="Back" click="changeSoundIndex(-1)"/>
<s:Button id="btnPlay" x="336" y="199" label="Button"/>
<s:Button id="btnStop" x="366" y="89" label="Stop"/>
<s:VScrollBar id="sldrPosition" x="280" y="43" mouseDown="thumbTimer.stop()"
mouseUp="thumbTimer.start()"
/>
<s:VScrollBar id="sldrVolume" x="265" y="234" change="ChangeSoundTransform()"
/>
<s:RichText id="txtID3" x="236" y="41" width="99">
</s:RichText>
<fx:Declarations>
</fx:Declarations>
<fx:Script>
<![CDATA[
import com.ericcarlisle.PlayList;
import com.ericcarlisle.PlayModes;
import com.ericcarlisle.Utility;
import flash.desktop.NativeDragManager;
import flash.media.Sound;
import mx.core.UIComponent;
import mx.events.CloseEvent;
import mx.events.DragEvent;
import org.osmf.traits.PlayTrait;
import spark.components.DataGrid;
// Player properties
private var playMode:String = "STOP";
private var volume:uint;
private const panning:int = 0;
private var selectedFileCount:uint;
private var loadedFileCount:uint;
private var soundIndex:uint;
// Player objects
private var SoundObj:Sound;
private var Channel:SoundChannel;
private var Transform:SoundTransform;
private var thumbTimer:Timer;
private var PlayList:com.ericcarlisle.PlayList;
private var SoundFilter:FileFilter = new FileFilter("Sounds", "*.mp3;*.wav");
//private var PlaylistFilter:FileFilter = new FileFilter("Sounds", "*.pls;*.m3u");
// Visualization objects.
private var Spectrum:ByteArray;
private const VISUALIZER_HEIGHT:Number = 50;
private const VISUALIZER_COLOR:Number = 0x336699;
// ID3 and other metadata
private var ID3:ID3Info;
private var Duration:int;
/*---------- PLAYER INITIALIZER ----------*/
// Initialization function used to add event handlers and set initial settings.
private function init():void
{
// Set player initial settings.
playMode = PlayModes.STOP;
selectedFileCount = 0;
loadedFileCount = 0;
soundIndex = 0;
// Set initial application height.
//this.height= cvsControlBar.height + cvsPlayer.height;
// Set volume.
volume = sldrVolume.value;
// Instantiate sound objects.
Channel = new SoundChannel();
Transform = new SoundTransform(volume/100, panning);
PlayList = new com.ericcarlisle.PlayList();
// Bind playlist data to datagrid.
dgPlaylist.dataProvider = PlayList.Sounds;
// Create a timer to control the song position hslider.
thumbTimer = new Timer(500);
thumbTimer.addEventListener(TimerEvent.TIMER, onTimerTick);
// Create event handlers for application.
this.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, onPlayerDragInto);
this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, onPlayerDropInto);
this.addEventListener(InvokeEvent.INVOKE, onInvoke);
}
/*---------- DRAG/DROP & FILE MANAGEMENT ----------*/
private function onInvoke(event:InvokeEvent):void
{
if (event.arguments.length > 0)
{
var file:File;
var files:Array = new Array();
for (var i:int = 0; i < event.arguments.length; i++)
{
file = new File(event.arguments[i]);
files.push(file);
}
if (PlayList.Sounds.length > 0) removeAllSounds();
loadFiles(files);
}
}
// Handles file selection event dispatched by browse dialog.
private function onFileSelect(event:FileListEvent):void
{
loadFiles(event.files);
}
// Handles folder selection event dispatched by browse dialog.
private function onDirectorySelect(event:Event):void
{
var directory:File = event.target as File;
**loadFiles(directory.getDirectoryListing());**
}
// Loads a batch of files into the playlist.
private function loadFiles(files:Array):void
{
var file:File;
// Count the number of files selected. Only accept files with .mp3 extension.
selectedFileCount = 0;
for (var i:uint = 0; i < files.length; i++)
{
file = files[i];
if (file.extension == "mp3") selectedFileCount++;
}
// Reset the count on files currently loaded.
loadedFileCount = 0;
**// Set the player mode so that loaded files are played automatically.
if (PlayList.Sounds.length == 0) playMode = PlayModes.LOADTOPLAY;**
// Load files as sound objects.
for(var j:uint = 0; j < files.length; j++)
{
file = files[j];
if (file.extension == "mp3" || file.extension == "wav")
{
var sound:Sound = new Sound(new URLRequest(file.url));
sound.addEventListener(Event.ID3,onID3);
}
}
}
// Presents file browse (multiple file) dialog.
private function browseForFiles():void
{
var SoundFile:File = new File();
SoundFile.browseForOpenMultiple("Open", [SoundFilter]);//, PlaylistFilter]);
SoundFile.addEventListener(FileListEvent.SELECT_MULTIPLE, onFileSelect);
}
// Presents file browse (folder) dialog.
private function browseForFolder():void
{
var directory:File = File.documentsDirectory;
directory.browseForDirectory("Select Directory");
directory.addEventListener(Event.SELECT, onDirectorySelect);
}
// Accept files dragged into player.
private function onPlayerDragInto(event:Event):void
{
NativeDragManager.acceptDragDrop(this);
}
// Manages files dropped into player.
private function onPlayerDropInto(event:NativeDragEvent):void
{
// Accept only files.
if (event.clipboard.hasFormat(ClipboardFormats.FILE_LIST_FORMAT))
{
// Parse dragged contents into array of files.
var dragFiles:Array = event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
// Load the files.
loadFiles(dragFiles);
}
}
/*---------- SOUND MANAGEMENT ----------*/
private function loadSound():void
{
SoundObj = new Sound();
SoundObj.load(new URLRequest(PlayList.Sounds[soundIndex]["url"]));
SoundObj.addEventListener(Event.COMPLETE, onSoundLoaded);
}
private function onSoundLoaded(event:Event):void
{
// Retrieve data for current sound from playlist.
var soundData:Object = PlayList.Sounds[soundIndex];
// Place ID3 information into the readout panel.
//txtID3.htmlText = Utility.ReadoutHTML(soundData["title"], soundData["track"], soundData["album"], soundData["artist"], soundData["year"], soundData["duration"]);
// Configure the holizontal slider to act as a playhead.
sldrPosition.maximum = soundData["duration"];
// Set the selected row in the playlist display.
dgPlaylist.selectedIndex = soundIndex;
// Start the player if the mode is correct.
if (playMode == PlayModes.LOADTOPLAY)
{
playSound();
}
else
{
playMode = PlayModes.LOADED;
}
}
// Plays the current sound.
public function playSound():void
{
// Load sound into channel.
Channel.stop();
Channel = SoundObj.play(sldrPosition.value,0,Transform);
playMode = PlayModes.PLAY;
// Start position timer.
thumbTimer.start();
// Configure UI controls.
btnPlay.visible = false;
btnPause.visible = true;
sldrPosition.enabled = true;
btnPlay.enabled = true;
btnStop.enabled = true;
setBackForwardButtons();
Channel.addEventListener(Event.SOUND_COMPLETE, onSoundComplete);
}
private function setBackForwardButtons():void
{
if (soundIndex == PlayList.Sounds.length-1 || PlayList.Sounds.length == 0)
{
btnForward.enabled = false;
}
else
{
btnForward.enabled = true;
}
if (soundIndex == 0 || PlayList.Sounds.length == 0)
{
btnBack.enabled = false;
}
else
{
btnBack.enabled = true;
}
}
// Stops the current sound.
public function stopSound():void
{
Channel.stop();
thumbTimer.stop();
sldrPosition.value = 0;
playMode = PlayModes.STOP;
//Visualizer.graphics.clear();
btnPlay.visible = true;
btnPause.visible = false;
}
// Pause a playing sound.
private function pauseSound():void
{
Channel.stop();
thumbTimer.stop();
btnPlay.visible = true;
btnPause.visible = false;
}
// Change the sound index
private function changeSoundIndex(delta:int):void
{
stopSound();
playMode = PlayModes.LOADTOPLAY;
soundIndex = soundIndex + delta;
loadSound();
}
// Change the volume and panning via the sound transform object.
private function ChangeSoundTransform():void
{
volume = Math.round(sldrVolume.value);
Channel.soundTransform = new SoundTransform(volume/100, panning);
}
// Handles event for sound completing.
private function onSoundComplete(event:Event):void
{
stopSound();
soundIndex++;
if (soundIndex < PlayList.Sounds.length)
{
playMode = PlayModes.LOADTOPLAY;
loadSound();
}
}
// Load ID3 information into local variables.
// Update the readout panel.
// Configure position slider.
private function onID3(event:Event):void
{
var sound:Sound = Sound(event.target);
ID3 = ID3Info(sound.id3);
Duration = Math.floor(sound.length);
// Load sound id3 data into the playlist.
PlayList.AddSound(ID3.songName, ID3.album, ID3.artist, ID3.track, ID3.year, ID3.genre, Duration, sound.url);
// Increment the loaded file count.
loadedFileCount++;
if (loadedFileCount == selectedFileCount * 2)
{
// Refresh the playlist so that new results will be visually displayed.
PlayList.Sounds.refresh();
// Set the count properties.
selectedFileCount = 0;
loadedFileCount = 0;
soundIndex = 0;
if (playMode == PlayModes.LOADTOPLAY) loadSound();
}
}
/*---------- VISUALIZATION ----------*/
private function UpdateVisualizer():void
{
// Instantiate a new byte array to contain spectrum data.
Spectrum = new ByteArray();
// Clear the visualizer graphics.
//Visualizer.graphics.clear();
// Dump the spectrum data into the byte array.
SoundMixer.computeSpectrum(Spectrum,false,0);
var f:Number;
var i:int;
var ave:int;
//Visualizer.graphics.lineStyle(1, VISUALIZER_COLOR,1);
//Visualizer.graphics.beginFill(VISUALIZER_COLOR, 0.75);
for (i = 0; i < 512; i=i+10)
{
f = Spectrum.readFloat();
//Visualizer.drawRoundRect(Math.floor(i*0.7) + 7, cvsReadout.height - 10, 4, -Math.abs(f) * (cvsReadout.height-10));
}
//Visualizer.graphics.endFill();
}
// Updates the position of the hslider thumb.
private function onTimerTick(event:TimerEvent):void
{
sldrPosition.value = Math.round(Channel.position);
}
// Update the wave visualizer if the sound is playing.
private function onEnterFrame(event:Event):void
{
if (playMode == PlayModes.PLAY)
{
UpdateVisualizer();
}
}
// Show application information.
private function showHowlerInfo():void
{
//cvsAbout.visible = true;
}
private function togglePlayList():void
{
}
private function onItemDoubleClick(event:Event):void
{
this.playMode = PlayModes.LOADTOPLAY;
thumbTimer.stop();
sldrPosition.value = 0;
loadSound();
}
/*---------- ERROR HANDLING ----------*/
// Handles IO errors.
private function onIOError(event:IOErrorEvent):void
{
//Alert.show("File load error: " + event.text);
}
private function startMove():void
{
stage.nativeWindow.startMove();
}
private function unloadSound():void
{
stopSound();
txtID3.text = "";
btnPlay.visible = true;
btnPause.visible = false;
btnPlay.enabled = false;
btnStop.enabled = false;
}
private function removeSound():void
{
var index:int = dgPlaylist.selectedIndex;
if (index >= 0)
{
if (index == soundIndex)
{
unloadSound();
}
PlayList.RemoveSoundAt(index);
PlayList.Sounds.refresh();
setBackForwardButtons();
}
}
private function removeAllSounds():void
{
unloadSound();
PlayList.Sounds.removeAll();
PlayList.Sounds.refresh();
setBackForwardButtons();
}
private function onKeyDown(event:KeyboardEvent):void
{
if (event.charCode.toString() == "8" || event.charCode.toString() == "127")
{
removeSound();
}
}
]]>
</fx:Script>
</s:View>
I'm new to Flex so I don't know if this is causing the problem or not, but the Howler app uses an MX:DataGrid defined like this:
<mx:DataGrid x="6"
y="7"
width="388"
height="310"
id="dgPlaylist"
keyDown="onKeyDown(event)"
dragMoveEnabled="true"
doubleClickEnabled="true"
dragEnabled="true"
dropEnabled="true"
dragComplete="onPlaylistDragDrop(event)"
itemDoubleClick="onItemDoubleClick(event)">
<mx:columns>
<mx:DataGridColumn width="168" headerText="Title" dataField="title" />
<mx:DataGridColumn width="160" headerText="Album" dataField="album"/>
<mx:DataGridColumn width="60" headerText="Duration" dataField="duration" textAlign="right" itemRenderer="components.DurationFormatter"/>
</mx:columns>
</mx:DataGrid>
It has additional columns that I'm not using. Could this be the cause?
We are going to need the error message. Generally what you are experiencing is called a null pointer exception ( just like the error said ). Which basically means you tried to access a property of an object that is null. For example, running the following code will cause the same problem
var arrayCollection:ArrayCollection;
arrayCollection.addItem( new Object() );
To fix your error, you should find the object that the error is referring to in your code and make sure it isn't null when your program executes whatever line it is complaining about, or add an if-loop in the event it is null.

Scaling multiple axes in PlotChart

When I programmatically create a PlotChart starting w/ no series and adding series w/ own scaling and verticalAxes (and Renderers but not necessary for behavior error), the axes and data show, but the default axis controls all scaling and the other axes are erroneous. Thus, the yValue magnitudes do not correspond to their associated axes and mixing series w/ grossly different orders of magnitude squishes all but the largest into indistinguishable floor values. I cannot null out the default vertical axis as it gets an null pointer error. [Click anywhere on the chart to add the next series.]
package
{
/*
* Attempt to dynamically create graph w/ varying series. Having difficulty getting axis to render correctly based
* on sets of series. Having trouble getting more than one series. I can't munge the yValue property because in my
* actual code all of the data elements are instances of the same class with properties akin to series, xValue, and yValue.
*
*/
import flash.events.MouseEvent;
import mx.charts.AxisRenderer;
import mx.charts.DateTimeAxis;
import mx.charts.LinearAxis;
import mx.charts.PlotChart;
import mx.charts.chartClasses.Series;
import mx.charts.events.ChartEvent;
import mx.charts.series.PlotSeries;
import mx.collections.ArrayCollection;
public class GraphSample extends PlotChart
{
public function GraphSample()
{
super();
this.selectionMode = "single";
this.percentWidth = 80;
this.series = new Array();
this.verticalAxisRenderers = new Array();
this.showDataTips = true;
}
protected override function createChildren():void {
super.createChildren();
// Create the horizontal axis
var hAxis:DateTimeAxis = new DateTimeAxis();
hAxis.dataUnits = "days";
this.horizontalAxis = hAxis;
// NOTE: I do not want an automatically created verticalAxis, but can't seem to avoid it
// Add vertical axis renderer
var axis:AxisRenderer = new AxisRenderer();
axis.axis = this.verticalAxis;
axis.horizontal = false;
axis.setStyle("showLabels", true);
axis.setStyle("showLine", true);
this.verticalAxisRenderers.push(axis);
this.verticalAxisRenderers = this.verticalAxisRenderers;
this.addEventListener(ChartEvent.CHART_CLICK, addSeries);
}
private var seriesColors:Array = [0x888888, 0xFFC833, 0xFF6433, 0xE73399,
0x8133CC, 0x346B9B, 0x33C399, 0x98F133];
private var seriesColorCursor:int = 0;
private const ONE_DAY:Number = (1000 * 60 * 60 * 24);
private const TODAY:Date = new Date();
private function addSeries(event:MouseEvent):void {
var dimension:Object = newDimension();
var series:Series = new PlotSeries();
series.displayName = dimension.name;
series.dataFunction = genericFieldRetriever;
series.setStyle("fill", seriesColors[seriesColorCursor++]);
if (seriesColorCursor > seriesColors.length) seriesColorCursor %= seriesColors.length;
series.dataProvider = dimension.elements;
this.series.push(series);
var seriesAxis:LinearAxis = new LinearAxis();
series.setAxis("verticalAxis", seriesAxis);
var min:Number = Number.MAX_VALUE, max:Number = 0;
for each (var ele:Object in series.dataProvider) {
if (ele.value > max) max = ele.value;
if (ele.value < min) min = ele.value;
}
seriesAxis.minimum = min * 0.85;
seriesAxis.maximum = max * 1.2;
seriesAxis.displayName = series.displayName;
seriesAxis.title = series.displayName;
// Add vertical axis renderer
var axis:AxisRenderer = new AxisRenderer();
axis.axis = seriesAxis;
axis.horizontal = false;
axis.setStyle("color", series.getStyle("fill"));
axis.setStyle("showLabels", true);
axis.setStyle("showLine", true);
this.verticalAxisRenderers.push(axis);
this.verticalAxisRenderers = this.verticalAxisRenderers;
// also strokes?
// http://www.flexdeveloper.eu/forums/flex-charting/creating-linecolumn-series-dynamically/
this.series = this.series;
this.invalidateSeriesStyles();
if (names.length == 0) this.removeEventListener(ChartEvent.CHART_CLICK, addSeries);
}
/**
* A fake of the server data retrieval mechanism.
* #return wrapper w/ name and elements set where each element has a data and value.
*/
private function newDimension():Object {
var result:Object = new Object();
result['name'] = names.shift();
var elements:ArrayCollection = new ArrayCollection();
var thisBase:int = base.shift();
var thisMax:int = maxAdd.shift();
for (var date:Date = new Date(TODAY.getTime() - 10 * ONE_DAY); date.getTime() <= TODAY.getTime(); date = new Date(date.getTime() + ONE_DAY)) {
var element:Object = new Object();
element['date'] = date;
element['value'] = thisBase + Math.random() * thisMax;
elements.addItem(element);
}
result['elements'] = elements;
return result;
}
private var names:Array = ['fat', 'carbs', 'steps', 'walking miles', 'pounds', 'cycling miles', 'running miles', 'skiing hours', 'lifting mins'];
private var base:Array = [0, 20, 1000, 0, 100, 0, 0, 0, 0];
private var maxAdd:Array = [100, 200, 9000, 4, 200, 40, 8, 3, 75];
private function genericFieldRetriever(series:Series, item:Object, fieldName:String):Object {
if(fieldName == 'yValue')
return(item.value);
else if(fieldName == "xValue")
return(item.date);
else
return null;
}
}
}
The problem was the line
series.setAxis("verticalAxis", seriesAxis);
That is not equivalent to
series.verticalAxis = seriesAxis;
Once I changed that, everything works perfectly, but it cannot handle the abstract Series class b/c that class does not have the setter for verticalAxis.

Resources