Problem with removeEventListener

Hi
I have a code:
package
     import adobe.utils.CustomActions;
     import flash.display.MovieClip;
     import flash.events.MouseEvent;
     import flash.text.TextField;
     import flash.events.*;
     import flash.utils.getTimer;
     public class MyMatching extends MovieClip
          public var play_btn:MyButton = new MyButton();//creating new object play_btn
          public var xIconsContainer=100;//all icons start to draw from this x
          public var yIconsContainer=100;//all icons start to draw from this y
          private var iconsVertical=2;//icons columns
          private var iconsHorizontal=2;//icons rows
          private var firstIcon;//player click to first icon
          private var secondIcon;//player click to second icon
          private var deletedIcons;//if firstIcon==secondIcon we will delete 2 icons
          //private var myTimer:MyTimer;
          public var startTime:int = getTimer();
          public var timeString:String;
          private var playerScoreSum:int;//sum of all players points
          private var playerScorePreview:TextField;//showing players points to the window
          private var matchPoints:int = 20;//if player match 2 icons we add 20 points to his playerScoreSum
          private var missPoints:int = 1;//if miss we delete 1 points from playerScoreSum
          //constructor
          public function MyMatching():void
               welcomeScreen();
               deletedIcons = 0;
               playerScoreSum = 0;
          public function welcomeScreen():void
               gotoAndStop('WelcomeScreen');
               play_btn.x=210;
               play_btn.y=300;
               play_btn.visible=true;
               addChild(play_btn);//draw play_btn object
               play_btn.addEventListener(MouseEvent.CLICK, goToLevel_1);//added event for the play_btn object
          public function startingStopwatch():void
               addEventListener(Event.ENTER_FRAME, stopwatch);
          public function stopingStopwatch():void
               removeEventListener(Event.ENTER_FRAME, stopwatch);
          public function stopwatch(event:Event)
               var timePassed:int = getTimer()-startTime;
               var seconds:int = Math.floor(timePassed/1000);
               var minutes:int = Math.floor(seconds/60);
               seconds -= minutes*60;
               timeString = minutes + ":" + String(seconds + 100).substr(1, 2);
               stopwatch_txt.text = timeString;
          public function goToLevel_1(event:MouseEvent)
               play_btn.visible=false;
               gotoAndStop('Level_1');
               startingStopwatch();
               var iconsArray:Array = new Array();//creating new object iconsArray
               for (var i:int; i < iconsVertical*iconsHorizontal/2; i++)
                    iconsArray.push(i);
                    iconsArray.push(i);
               trace(iconsArray);
               //added timer to the screen
               //myTimer = new MyTimer();
               //addChild(myTimer);
               //added score to the sceen
               playerScorePreview = new TextField();
               playerScorePreview.text = String(playerScoreSum);
               playerScorePreview.x=200;
               playerScorePreview.y=0;
               addChild(playerScorePreview);
               for (var x:int = 0; x < iconsVertical; x++)
                    for (var y:int = 0; y < iconsHorizontal; y++)
                         var iconsList:Icon = new Icon();
                         addChild(iconsList);
                         iconsList.stop();
                         iconsList.x=x*51+xIconsContainer;
                         iconsList.y=y*51+yIconsContainer;
                         var myRandom:int=Math.floor(Math.random()*iconsArray.length);//creates a random number that will be related to an index of the array named "iconsArray"
                         //var showIcon;//cast as whatever type of element the array is holding
                         iconsList.showIcon=iconsArray[myRandom];//assigns the randomly selected element of iconsArray to the variable showIcon
                         iconsArray.splice(myRandom,1);//removes the randomly selected element (now showIcon) from the array (not the last one, the random one) //we use the splice command to remove number from the array so that it won’t be used again
                         //iconsList.gotoAndStop(iconsList.showIcon+2);//showIcon+2 would be the next frame in the timeline after the frame for the random item deleted, so that code is essentially moving in the timeline to the frame just after the frame for the item that was removed from the array
                         trace(myRandom);
                         iconsList.addEventListener(MouseEvent.CLICK, clickToIcon);
                         deletedIcons++;//when we draw icons we every time add +2 icons to our deletedIcons variable, in future we will deleted 2 icons from this variable if firstIcon==secondIcon
               trace("*************************random finished ******************************");
          public function clickToIcon(event:MouseEvent)
               var thisIcon:Icon = (event.currentTarget as Icon);//what icon player clicked...
               trace(thisIcon.showIcon);//trace clicked icon to the output pannel
               if (firstIcon==null)
                    firstIcon=thisIcon;
                    firstIcon.gotoAndStop(thisIcon.showIcon + 2);
               else if (firstIcon == thisIcon)
                    firstIcon.gotoAndStop(1);
                    firstIcon=null;
               else if (secondIcon==null)
                    secondIcon=thisIcon;
                    secondIcon.gotoAndStop(thisIcon.showIcon + 2);
                    if (firstIcon.showIcon==secondIcon.showIcon)
                         playerScoreSum += matchPoints;// +20 points for playerScoreSum
                         playerScorePreview.text = String(playerScoreSum);
                         removeChild(firstIcon);
                         removeChild(secondIcon);
                         deletedIcons -= 2;
                         if (deletedIcons == 0)
                              //myTimer.Stop();//stoping timer, so now we know how time player spend to playing the level 1
                              stopingStopwatch();
                              stopwatch_txt.text = timeString;//why i don't see time?
                              gotoAndStop('GameoverScreen');//if player match all icons we go to GameoverScreen                              
                    else
                         playerScoreSum -= missPoints;// -1 point from playerScoreSum
                         playerScorePreview.text = String(playerScoreSum);
               else
                    firstIcon.gotoAndStop(1);
                    secondIcon.gotoAndStop(1);
                    firstIcon = null;
                    secondIcon = null;
There problem with my timer.
Code for timer:
public var startTime:int = getTimer();
          public var timeString:String;
public function startingStopwatch():void
               addEventListener(Event.ENTER_FRAME, stopwatch);
          public function stopingStopwatch():void
               removeEventListener(Event.ENTER_FRAME, stopwatch);
          public function stopwatch(event:Event)
               var timePassed:int = getTimer()-startTime;
               var seconds:int = Math.floor(timePassed/1000);
               var minutes:int = Math.floor(seconds/60);
               seconds -= minutes*60;
               timeString = minutes + ":" + String(seconds + 100).substr(1, 2);
               stopwatch_txt.text = timeString;
When i come to function 'goToLevel_1' i start funciton 'startingStopwatch();'
So all working i see my stopwatching.. time going..
Then when i go to gameover screen i don't see a timer:
if (deletedIcons == 0)
                              //myTimer.Stop();//stoping timer, so now we know how time player spend to playing the level 1
                              stopingStopwatch();
                              stopwatch_txt.text = timeString;//why i don't see time?
                              gotoAndStop('GameoverScreen');//if player match all icons we go to GameoverScreen                              
Why its happend?
And one more question:
When i click to play_btn i see error in output window:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at MyMatching/stopwatch()
how i can fix it?
Thank you.

The 1009 error indicates that one of the objects being targeted by your code is out of scope, and I suspect it involves your stopwatch_txt textfield.  This could mean that the object....
- is not in the display list
- doesn't have an instance name (or the instance name is mispelled)
- does not exist in the frame where that code is trying to talk to it
- is animated into place but is not assigned instance names in every keyframe for it
- is one of two or more consecutive keyframes of the same objects with different names assigned.
If you go into your Publish Settings Flash section and select the option to Permit debugging, your error message should have a line number following the frame number which will help you isolate which object is involved.

Similar Messages

  • Having problems with removeEventListener with two different MouseEvents

    I'm trying to get the children of _banner to do 2 things simultaneously, and I'm not getting it to work properly. I wanted them to all tween down the stage (navTween2), and remove the first MouseEvent listener so I can use a second one to execute a separate method on another mouse click, but it keeps firing off the onClick1. I'm currently testing this on the navHome iteration of _navButton before implementing it across the rest of them. What am I missing? Any advice would be appreciated
    package {
        import flash.display.MovieClip;
        import NavButton;//load nav class
        import flash.events.Event;
        import fl.transitions.Tween;
        import fl.transitions.TweenEvent;
        import fl.transitions.easing.*;
        import flash.net.*;
        import flash.events.MouseEvent;
        import flash.text.*;
        public class ZDSite extends MovieClip {
            private var _navButton:NavButton;
            private var _banner:Banner;
            private var total:Number=stage.loaderInfo.bytesTotal;
            private var loaded:Number=stage.loaderInfo.bytesLoaded;
            private var banTween:Tween;
            private var banTween2:Tween;
            private var navTween:Tween;
            private var navTween2:Tween;
            private var xmlLoader:URLLoader = new URLLoader();
            private var xml:XML;
            private var xmlList:XMLList;
            private var navX:Number;
            private var navY:Number;
            private var navSpace:Number;
            private var fadeIn:Tween;
            function ZDSite() {
                //Run preloader
                addEventListener(Event.ENTER_FRAME,loadSite);
            private function loadSite(event:Event):void {
                Bar_mc.scaleX = loaded/total;
                txtLoaded.text = Math.floor((loaded/total)*100)+"%";
                if (total == loaded) {
                    removeChild(txtLoaded);//remove from stage
                    removeChild(Bar_mc);//remove from stage
                    removeChild(plBracket_mc);//remove from stage
                    removeEventListener(Event.ENTER_FRAME,loadSite);
                    trace("site loaded, starting opening animation and executing nav build");
                    IntroAnim_mc.addEventListener("imdone", createBanner);
                    IntroAnim_mc.play();
                    xmlLoad();
            //add banner
            public function createBanner(event:Event):void {
                IntroAnim_mc.removeEventListener("imdone", createBanner);
                _banner = new Banner;
                addChild(_banner);
                _banner.y = 1152;
                banTween = new Tween(_banner, "y", Back.easeOut, 1152, 155, .5, true);
                //Execute createNav AFTER this tween is done
                banTween.addEventListener(TweenEvent.MOTION_FINISH, createNav);
            //load XML for nav buttons
            private function xmlLoad() {
                xmlLoader.load(new URLRequest("data/navigation.xml"));
                xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
            //check to see if XML is loaded
            private function xmlLoaded(event:Event):void {
                trace(event.target.data);//show the raw XML
                xml = XML(event.target.data);
                xmlList = xml.children();
                trace(xmlList.length());//show the # of nodes
            //add the nav buttons on the stage
            public function createNav(e:TweenEvent) {
                //set nav start position and spacing here
                navX = 130;
                navY = 330;
                navSpace = 5;
                //add nav buttons per XML data
                for (var i:int = 0; i < xmlList.length(); i++) {
                    _navButton = new NavButton;
                    addChild(_navButton);
                    //name each instance per XML data
                    _navButton.name = xmlList[i];
                    _navButton.x = navX;
                    //Animate and fade in each instance of _navButton
                    navTween = new Tween(_navButton, "y", Elastic.easeOut, 600, navY, 1, true);
                    fadeIn = new Tween(_navButton, "alpha", None.easeNone, 0, 1, 1, true);
                    //change text in each iteration of _navButton per XML data
                    _navButton.navTitle.navText.text = xmlList[i];
                    //add space between navs
                    navX += _navButton.width + navSpace;
                    trace(_navButton.name);
                    //add event listener to each iteration
                    _navButton.addEventListener(MouseEvent.CLICK, onClick1);
            //Set onClick function for each nav button added
            function onClick1(event:MouseEvent):void {
                _navButton.removeEventListener(MouseEvent.CLICK, onClick1); //this isn't being removed, why?
                banTween2 = new Tween(_banner, "y", Back.easeOut, 155, 300, 1, true);
                navTween2 = new Tween(event.currentTarget, "y", Back.easeInOut, navY, 400, 1, true);
                //How would I implement navTween2 across all _navButtons?
                if (event.currentTarget.name == "Home") {
                    _navButton.addEventListener(MouseEvent.CLICK, navHome);
                if (event.currentTarget.name =="Bio") {
                    navBio();
                if (event.currentTarget.name == "Flash") {
                    navFlash();
                if (event.currentTarget.name == "Print") {
                    navPrint();
                if (event.currentTarget.name == "Web") {
                    navWeb();
                if (event.currentTarget.name == "Art") {
                    navArt();
            //button nav functions
            //Home
            public function navHome():void {
                trace("Home has been clicked");
            //Bio
            public function navBio():void {
                trace("Bio has been clicked");
            //Flash
            public function navFlash():void {
                trace("Flash has been clicked");
            //Print
            public function navPrint():void {
                trace("Print has been clicked");
            //Web
            public function navWeb():void {
                trace("Web has been clicked");
            //Art
            public function navArt():void {
                trace("Art has been clicked");

    Ah okay, I apologize for the confusion at the end of the script there. What my intent is that after animating the navButtons after the first click, I am going to have them call in another movie clip from the library (e.g. the different portfolio galleries) when clicked a second time. I guess I didn't see the redundancy in trying to fix my original problem.
    What this is, is my attempt to reverse-engineer this template I saw online using AS 3 and XML:
    http://www.templatemonster.com/flash-templates/22017.html
    I cleaned up the code a bit further, including your suggestions and I'm now getting closer to what I'm trying to achieve. My only remaining query would be the best way to get the navs to stay "up" after being clicked (as well as reverting the others back to their original state) taking into consideration that the over/out functions reside in the NavButton class from the document's class. Your help has been EXTREMELY helpful! Code below:
    package {
        import flash.display.MovieClip;
        import NavButton;//load nav class
        import flash.events.Event;
        import fl.transitions.Tween;
        import fl.transitions.TweenEvent;
        import fl.transitions.easing.*;
        import flash.net.*;
        import flash.events.MouseEvent;
        import flash.text.*;
        public class ZDSite extends MovieClip {
            private var _navButton:NavButton;
            private var _navButtons:Array=[];
            private var _banner:Banner;
            private var total:Number=stage.loaderInfo.bytesTotal;
            private var loaded:Number=stage.loaderInfo.bytesLoaded;
            private var banTween:Tween;
            private var banTween2:Tween;
            private var navTween:Tween;
            private var navTween2:Tween;
            private var xmlLoader:URLLoader = new URLLoader();
            private var xml:XML;
            private var xmlList:XMLList;
            private var navX:Number;
            private var navY:Number;
            private var navSpace:Number;
            private var fadeIn:Tween;
            function ZDSite() {
                //Run preloader
                addEventListener(Event.ENTER_FRAME,loadSite);
            private function loadSite(event:Event):void {
                Bar_mc.scaleX = loaded/total;
                txtLoaded.text = Math.floor((loaded/total)*100)+"%";
                if (total == loaded) {
                    removeChild(txtLoaded);//remove from stage
                    removeChild(Bar_mc);//remove from stage
                    removeChild(plBracket_mc);//remove from stage
                    removeEventListener(Event.ENTER_FRAME,loadSite);
                    trace("site loaded, starting opening animation and executing nav build");
                    IntroAnim_mc.addEventListener("imdone", createBanner);
                    IntroAnim_mc.play();
                    xmlLoad();
            //add banner
            public function createBanner(event:Event):void {
                IntroAnim_mc.removeEventListener("imdone", createBanner);
                _banner = new Banner;
                addChild(_banner);
                _banner.y = 1152;
                banTween = new Tween(_banner, "y", Back.easeOut, 1152, 155, .5, true);
                //Execute createNav AFTER this tween is done
                banTween.addEventListener(TweenEvent.MOTION_FINISH, createNav);
            //load XML for nav buttons
            private function xmlLoad() {
                xmlLoader.load(new URLRequest("data/navigation.xml"));
                xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
            //check to see if XML is loaded
            private function xmlLoaded(event:Event):void {
                trace(event.target.data);//show the raw XML
                xml = XML(event.target.data);
                xmlList = xml.children();
                trace(xmlList.length());//show the # of nodes
            //add the nav buttons on the stage
            public function createNav(e:TweenEvent) {
                //set nav start position and spacing here
                navX = 130;
                navY = 330;
                navSpace = 5;
                var _navButton:NavButton;
                //add nav buttons per XML data
                for (var i:int = 0; i < xmlList.length(); i++) {
                    _navButton = new NavButton;
                    _navButtons.push(_navButton);
                    addChild(_navButton);
                    //name each instance per XML data
                    _navButton.name = xmlList[i];
                    _navButton.x = navX;
                    //Animate and fade in each instance of _navButton
                    navTween = new Tween(_navButton, "y", Elastic.easeOut, 600, navY, 1, true);
                    fadeIn = new Tween(_navButton, "alpha", None.easeNone, 0, 1, 1, true);
                    //change text in each iteration of _navButton per XML data
                    _navButton.navTitle.navText.text = xmlList[i];
                    //add space between navs
                    navX += _navButton.width + navSpace;
                    trace(_navButton.name);
                    //add event listener to each iteration
                    _navButton.addEventListener(MouseEvent.CLICK, onClick1);
            private var _tweens:Array=[];
            //Set onClick function for each nav button added
            function onClick1(event:MouseEvent):void {
                for each (var navButton:NavButton in _navButtons) {
                    navButton.removeEventListener(MouseEvent.CLICK, onClick1);//this isn't being removed, why?
                    navButton.addEventListener(MouseEvent.CLICK, onClick2);
                    banTween2 = new Tween(_banner, "y", Back.easeOut, 155, 300, 1, true);
                    _tweens.push(new Tween(navButton, "y", Back.easeInOut, navY, 400, 1, true));
            //Suggestions are welcome here!
            function onClick2(event:MouseEvent):void {
                if (event.currentTarget.name == "Home") {
                    trace("Home has been clicked");
                    //insert code to keep this._navButton.balloon_mc visible in the "over" state
                    //insert code to return all other _navButton.balloon_mc in their "up" states
                    //insert code to remove other galleries
                    //insert code to (re)insert "Home_mc" from library
                if (event.currentTarget.name =="Bio") {
                    trace("Bio has been clicked");
                    //insert code to keep this._navButton.balloon_mc visible in the "over" state
                    //insert code to return all other _navButton.balloon_mc in their "up" states
                    //insert code to remove other galleries
                    //insert code to (re)insert "Bio_mc" from library
                if (event.currentTarget.name == "Flash") {
                    trace("Flash has been clicked");
                    //insert code to keep this._navButton.balloon_mc visible in the "over" state
                    //insert code to return all other _navButton.balloon_mc in their "up" states
                    //insert code to remove other galleries
                    //insert code to (re)insert "Flash_mc" from library
                if (event.currentTarget.name == "Print") {
                    trace("Print has been clicked");
                    //insert code to keep this._navButton.balloon_mc visible in the "over" state
                    //insert code to return all other _navButton.balloon_mc in their "up" states
                    //insert code to remove other galleries
                    //insert code to (re)insert "Print_mc" from library
                if (event.currentTarget.name == "Web") {
                    trace("Web has been clicked");
                    //insert code to keep this._navButton.balloon_mc visible in the "over" state
                    //insert code to return all other _navButton.balloon_mc in their "up" states
                    //insert code to remove other galleries
                    //insert code to (re)insert "Web_mc" from library
                if (event.currentTarget.name == "Art") {
                    trace("Art has been clicked");
                    //insert code to keep this._navButton.balloon_mc visible in the "over" state
                    //insert code to return all other _navButton.balloon_mc in their "up" states
                    //insert code to remove other galleries
                    //insert code to (re)insert "Art_mc" from library

  • Problem with Tweens and HitTest

    Hi guys,
    I have a problem with by code generated Tweens and HitTest.
    But first of all the backgeround info. I have a couple of dots. They are generated from a single movieclip and differ in scale. The idea is, that the biggest one ist set to the middle position of the stage.
    The others are coming from the outer stage border and are moving towards the middle position. This is done by using the Tween class.
    What should happen is, that they stop exactly at the border of the dots which are already in the middle. In the beginning there is just the main, big dot which was manually positioned to the middle. When the first dot reached its position, the bounding box should include this new dot.
    I use the hitTestObjects method to stop the Tweeing.
    The problem is, that there is a 80% chance that the dots have gaps or overlapping each other. Any thoughts on that?
    Thanks for every reply!
    This is the hitTesting Code in the main class:
    public function hitTesting(e:Event):void{
                                  for(var i:int=0; i<dotArray.length;i++){
                                                      for(var j:int=i+1; j<dotArray.length;j++){
                                                                if(dotArray[i].hitTestObject(dotArray[j])==true){
                                                                          dotArray[i].stopTweening();
                                                                          dotArray[j].stopTweening();
    This is the code for a single Dot
    public function Dot(anchorArray:Array,randomX:int,randomY:int,scaleVal:Number,first:Boolean, delayVal:Number, lastElement:Boolean, values:Array) {
         this.x=randomX;
         this.y=randomY;
         this.scaleX=this.scaleY=scaleVal;
         this.valueName=values[0];
         this.countValue=values[1];
         this.gRanking=values[2]
         this.lastElement= lastElement;
         this.first=first;
          if(!first){
               this.xTween = new Tween(this, "x", None.easeNone, this.x, anchorArray[0], 20, false);
               this.yTween = new Tween(this, "y", None.easeNone, this.y, anchorArray[1], 20, false);
               this.xTween.start();
               this.yTween.start();
    public function stopTweening():void{
      if(!first){
          if(lastElement)
               parent.removeEventListener(Event.ENTER_FRAME, parent.hitTesting);
          xTween.stop();
          yTween.stop();

    Ok guys,
    found a solution. It seems to be, that the build in HitTest functionality is to inaccurate for my problem.
    I found a better implementation here.
    Tanks for reading.
    -alex

  • Problem with drag and drop

    Hi! I'm having a problem with getting this code working, basically I want to drag and drop two things onto another the things dissapear then it moves onto a new page, the first item works properly but then the second item wont dissapear and remains stuck to the cursor. Heres the code I'd be greatful of any help.
    import flash.events.MouseEvent;
    import fl.motion.MotionEvent;
    stop();
    Back6_btn.addEventListener(MouseEvent.CLICK, onBack6Click)
    function onBack6Click(event:MouseEvent):void{
        gotoAndPlay("Bedroom2");
        Forward6_btn.addEventListener(MouseEvent.CLICK, onForward6Click)
    function onForward6Click(event:MouseEvent):void{
        gotoAndPlay('Brother bit');
    var inGran:Number=0;
    Gin.addEventListener(MouseEvent.MOUSE_DOWN, dragOn);
    Tonic.addEventListener(MouseEvent.MOUSE_DOWN, dragOn);
    function dragOn(event:MouseEvent):void {
        event.target.startDrag(false);
        stage.addEventListener(MouseEvent.MOUSE_UP, dragOff);
    function dragOff(event:MouseEvent):void {
        event.target.stopDrag();
        if (event.target.dropTarget!=null&&event.target.dropTarget.parent==Gran) {
            event.target.visible=false;
            inGran++;
        stage.removeEventListener(MouseEvent.MOUSE_UP, dragOff);
    function checkPage(e:Event):void {
        if (inGran==2) {
            gotoAndPlay("Bedroom1");

    you have some mismatched brackets, change your target properties to currentTarget (and i'm not sure you're dropping onto the correct target) but, try:
    import flash.events.MouseEvent;
    import fl.motion.MotionEvent;
    stop();
    Back6_btn.addEventListener(MouseEvent.CLICK, onBack6Click)
    function onBack6Click(event:MouseEvent):void{
        gotoAndPlay("Bedroom2");
        Forward6_btn.addEventListener(MouseEvent.CLICK, onForward6Click)
    function onForward6Click(event:MouseEvent):void{
        gotoAndPlay('Brother bit');
    var inGran:Number=0;
    Gin.addEventListener(MouseEvent.MOUSE_DOWN, dragOn);
    Tonic.addEventListener(MouseEvent.MOUSE_DOWN, dragOn);
    function dragOn(event:MouseEvent):void {
    event.currentTarget.parent.addChild(event.currentTarget);
        event.target.startDrag(false);
        stage.addEventListener(MouseEvent.MOUSE_UP, dragOff);
    function dragOff(event:MouseEvent):void {
        event.target.stopDrag();
        if (event.target.dropTarget!=null&&event.target.dropTarget.parent==Gran) {
            event.target.visible=false;
            inGran++;
        stage.removeEventListener(MouseEvent.MOUSE_UP, dragOff);
    function checkPage(e:Event):void {
        if (inGran==2) {
            gotoAndPlay("Bedroom1");

  • Problem with XML loading and xmlns

    I'm having a problem with loading an XML file that was created by Filemaker.  Filemaker will output an XML file using one of two different grammars.  One outputs in a mostly standard form that I can use with one glitch.  Flash CS4 AS3 seems to have a problem with the xmlns in one of the nodes.
    Specifically:
    <FMPDSORESULT xmlns="http://www.filemaker.com/fmpdsoresult">
    If I remove the xmlns="http://www.filemaker.com/fmpdsoresult" the file loads properly and I can access the various fields with no problem.  However, when I leave the xmlns=... in, it will trace out the XML properly but I can't access the fields using the code listed below.  This is driving me crazy!
    With the xmlns part in the XML file I get the following error when it tries to load the thumbnail files:
    TypeError: Error #1010: A term is undefined and has no properties.
    I need to have it so that the user can enter/edit data and simply output the XML file from Filemaker and then Flash will load up the unaltered XML file and show the info requested by the user.  That is to say I could have the user open the XML file in a word processing application and have them delete the xmlns..., but that is rather cumbersome and not very user friendly.
    I've tried every xml.ignore function I could find but it doesn't help.  Hopefully someone out there can help
    Thanks,
    -Mark-
    Partial XML:
    XML From Filemaker Export:
    <?xml version="1.0" encoding="UTF-8" ?>
    <!-- This grammar has been deprecated - use FMPXMLRESULT instead -->
    <FMPDSORESULT xmlns="http://www.filemaker.com/fmpdsoresult">
      <ERRORCODE>0</ERRORCODE>
      <DATABASE>Sport.fp7</DATABASE>
      <LAYOUT></LAYOUT>
      <ROW MODID="1" RECORDID="1">
        <FirstName>Mark</FirstName>
        <LastName>Fowle</LastName>
        <Sport>Sailing</Sport>
        <Medal>None</Medal>
        <CourseOfStudy>Design</CourseOfStudy>
        <Year>1976-1978</Year>
        <HomeState>California</HomeState>
        <ImageName>93</ImageName>
      </ROW>
    </FMPDSORESULT>
    AS3 Code:
    import fl.containers.UILoader;
    var aPhoto:Array=new Array(ldPhoto_0,ldPhoto_1,ldPhoto_2,ldPhoto_3,ldPhoto_4,ldPhoto_5);
    var toSet:int=10;//time out set time
    var toTime:int=toSet;
    var photoPerPage:int=6;
    var fromPos:int=photoPerPage;
    var imgNum:Number;
    //var subjectURL:URLRequest=new URLRequest("testData_FM8.xml");
    var subjectURL:URLRequest=new URLRequest("Sports.xml");
    var xmlLoader:URLLoader=new URLLoader(subjectURL);
    xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
    var subjectXML:XML = new XML();
    subjectXML.ignoreWhitespace=true;
    subjectXML.ignoreComments=true;
    subjectXML.ignoreProcessingInstructions=true;
    function xmlLoaded(evt:Event):void {
        subjectXML=XML(xmlLoader.data);
        if (root.loaderInfo.bytesTotal==root.loaderInfo.bytesLoaded) {
            removeEventListener(Event.ENTER_FRAME, xmlLoaded);
            trace("XML Data File Loaded");
            trace(subjectXML);
        } else {
            trace("File not Found");
        imgNum=2;//subjectXML.ROW.length;
        trace(subjectXML);
        loadThumb(0);
    function loadThumb(startPos:int):void {
        var count:Number=aPhoto.length;
        trace(subjectXML.DATABASE);
        for (var i=0; i<count; i++) {
        try{
            aPhoto[i].source="images/"+subjectXML.ROW[startPos+i].ImageName+"_main.jpg";
        }catch (e:Error){
            trace(e);
            aPhoto[i].mouseChildren=false;
            aPhoto[i].addEventListener(MouseEvent.MOUSE_DOWN, onThumbClick);
        trace("Current mem: " + System.totalMemory);
        ldAttract.visible=false;
    function unloadThumb():void {
        var count:Number=aPhoto.length;
        for (var i=0; i<count; i++) {
            aPhoto[i].unload();
            aPhoto[i].removeEventListener(MouseEvent.MOUSE_DOWN, onThumbClick);
        trace("Current mem: " + System.totalMemory);
    function onThumbClick(evt:MouseEvent) {
        var i:Number;
        //trace("Thumbnail Clicked " + evt.target.name);
        i=findPos(evt.target.name);
        ldLrgPhoto.source="images/"+subjectXML.ROW[i+fromPos].LOCAL_OBJECT_ID+"_main.jpg";
        ldLrgPhoto.visible=true;
        btnPrev.visible=false;
        btnNext.visible=false;
        gotoAndStop("showPhoto");
    function findPos(thumb:String):Number {
        var pos:Number;
        var count:Number=aPhoto.length;
        for (var i:Number=0; i<count; i++) {
            if (thumb==aPhoto[i].name) {
                pos=i;
        return pos;

    Hi,
    I was trying to use xml namespaces, so in my application I receive an XML file from the server. The file has a namespace, so when I parse the file I need to specify the namespace:
    I got the following piece of xml:
    <ls:exchange xmlns:ls=".../tsw" xmlns:tm="http://kxa">
        <ls:projects>
             <tm:annotation id="" date="" action="getprojects" status="responseok"/>         
        <ls:project id="" name="proj" description="..." owner="asss"  release="2" />
            <ls:projectV  id="" version="" creationdate="" modificationdate=""/ >
        </ls:project>
    </ls:projects>
    </ls:exchange>
    and the following code
    <mx:VBox label="WELCOME" verticalScrollPolicy="off" horizontalScrollPolicy="off">
          <mx:Tree id="tree" dataProvider="{srv.lastResult.project}" labelField="@name"  width="300" height="100%" itemOpen="itemOpenEvt(event);" />
    </mx:VBox>
    So i want to display the content of the xml (project nodes”) in a tree view, but i don’t know how to includes the namespace"ls:" in the data provider “srv.lastResult.project”. can u help me it’s urgent.
    sincerly
    Celine

  • Having Problems with removing an addEventListener

    Greetings Adobe community,
    Im currently having a problem with my flash assignment,
    I have a:   this.addEventListener(Event.ENTER_FRAME, onPanSpace);
    who is causing errors when I go to the next frame:
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
              at Confabulation_fla::mc2_3/onPanSpace()[Confabulation_fla.mc2_3::frame1:13]
    I would like to remove this addEventListener when I go to the next frame(which is by clicking on a door) but to be honest, I have no clue how.
    So I ask you "How do I remove this addEventListener on my next frame?"
    Kind Regards
    Notnao

    function addTheListeners():void {
         addEventListener(Event.ENTER_FRAME, onPanSpace);
         addEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
    var snelheidNum:Number = 0.5;
    var snelheid:Number = 0;
    var MouseIsLinks:Boolean;
    function onPanSpace(e:Event):void
              var afstand:Number = Math.round(this.x - this.bg1.x);
              var percentage:Number = Math.floor((100 * afstand) / (this.bg1.width - root.stage.stageWidth));
              snelheid = -((root.stage.mouseX - (root.stage.stageWidth / 2))/110)/snelheidNum;
              if(root.stage.mouseX < (root.stage.stageWidth / 2)) { MouseIsLinks = true }
              if(root.stage.mouseX > (root.stage.stageWidth / 2)) { MouseIsLinks = false }
              if( (percentage < (1 - 100) && MouseIsLinks) || (percentage > (80 - 100) && !MouseIsLinks)) {snelheid = 0;}
              this.bg1.x += (snelheid / 1);
    function cleanUp(e:Event):void {
         removeEventListener(Event.ENTER_FRAME, onPanSpace);
         removeEventListener(Event.REMOVED_FROM_STAGE, cleanUp);
    //this.addEventListener(Event.ENTER_FRAME, onPanSpace);
    stop();
    This is what I got now, It removes the addeventListeners and I have no problems at the next frame but now my first frame doesnt have the onPanspace effect.

  • I have some problems with work in Flash cs6

    I have some problem with my game when I created it using adobe flash cs6
    When the duck hits the screen, like from right to left it shows
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
      at Duck/ducksmove()
      at flash.utils::Timer/_timerDispatch()
      at flash.utils::Timer/tick()
    This is the code so please help check which is wrong
    package  {
      import flash.display.MovieClip;
      import flash.utils.Timer;
      import flash.events.TimerEvent;
      import flash.events.MouseEvent;
      public class Duck extends MovieClip {
      var moveDuck:Timer = new Timer(10);
      var speedX:Number;
      public function Duck() {
      this.addEventListener(MouseEvent.CLICK,KillDuck);
      moveDuck.addEventListener(TimerEvent.TIMER,ducksmove);
      moveDuck.start();
      speedX = 10;
            function ducksmove(evt:TimerEvent):void
      this.x -= speedX;
      if (this.x <=0)
      moveDuck.stop();
      moveDuck.removeEventListener(TimerEvent.TIMER,ducksmove);
      this.parent.removeChild(this);
      function KillDuck(evt:MouseEvent):void
      var p:MovieClip = this.parent as MovieClip;
      p.setScore();
      p.updatecount();
      this.removeEventListener(MouseEvent.CLICK,KillDuck);
      this.parent.removeChild(this);
      moveDuck.addEventListener(TimerEvent.TIMER,ducksmove);

    You appear to be trying to remove the same object twice, first in the KillDuck function and then in the ducksmove function.  If it is removed already you can't try to remove it again because it is no longer in the display list.

  • Whats the problem with this page

    hi,
    i have problem with this page
    page
    it loading the video but not showing any content related to
    the video.
    i use
    [code]
    var netCon:NetConnection = new NetConnection();
    netCon.connect(null);
    var netStr:NetStream = new NetStream(netCon);
    netStr.addEventListener(AsyncErrorEvent.ASYNC_ERROR,
    getError);
    var video:Video = new Video();
    video.attachNetStream(netStr);
    addChild(video);
    video.x=201;
    video.y=125;
    function getError(e:AsyncErrorEvent) {
    play_btn.addEventListener(MouseEvent.MOUSE_DOWN, playVideo);
    function playVideo(e:MouseEvent) {
    netStr.resume();
    removeEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler
    this.addEventListener(Event.ENTER_FRAME, fileLoaded);
    var loaderBar:Sprite = new Sprite();
    addChild(loaderBar);
    function fileLoaded(e:Event) {
    var percent:Number = (netStr.bytesLoaded * 100 ) /
    netStr.bytesTotal;
    loaderBar.graphics.clear();
    loaderBar.graphics.beginFill(0xDE2C18);
    loaderBar.graphics.drawRect(205,378,percent * 4.32,5);
    loaderBar.graphics.endFill();
    if (percent==100) {
    this.removeEventListener(Event.ENTER_FRAME, fileLoaded);
    [/code]

    here is the full code
    and i have an error saying:
    ArgumentError: Error #2004: One of the parameters is
    invalid.
    at flash.display::Graphics/drawRect()
    at VIDEOPLAYER_fla::MainTimeline/fileLoaded()
    [code]
    import flash.display.Sprite;
    import flash.net.NetConnection;
    import flash.display.SimpleButton;
    import flash.net.NetStream;
    import flash.events.NetStatusEvent;
    import flash.media.Video;
    import flash.events.MouseEvent;
    import flash.events.KeyboardEvent;
    import flash.events.Event;
    import flash.display.Graphics;
    import flash.text.*;
    var netCon:NetConnection = new NetConnection();
    netCon.connect(null);
    var netStr:NetStream = new NetStream(netCon);
    netStr.addEventListener(AsyncErrorEvent.ASYNC_ERROR,
    getError);
    var URL:String =
    "/hakans/videos/BEDUK_AUTOMATIK00.flv?start=";
    var offset:uint = 1048576;
    var tamURL:String = URL + offset;
    trace(tamURL);
    var video:Video = new Video();
    video.attachNetStream(netStr);
    video.x=201;
    video.y=125;
    netCon = new NetConnection();
    netCon.addEventListener(NetStatusEvent.NET_STATUS,
    netStatusHandler);
    netCon.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
    securityErrorHandler);
    function netStatusHandler(event:NetStatusEvent):void {
    switch (event.info.code) {
    case "NetConnection.Connect.Success":
    connectStream();
    break;
    case "NetStream.Play.StreamNotFound":
    trace("Unable to locate video: " + tamURL);
    break;
    function connectStream():void {
    netStr.addEventListener(NetStatusEvent.NET_STATUS,
    netStatusHandler);
    netStr.addEventListener(AsyncErrorEvent.ASYNC_ERROR,
    asyncErrorHandler);
    netStr.play(tamURL);
    addChild(video);
    function securityErrorHandler(event:SecurityErrorEvent):void
    trace("securityErrorHandler: " + event);
    function asyncErrorHandler(event:AsyncErrorEvent):void {
    // ignore AsyncErrorEvent events.
    function getError(e:AsyncErrorEvent) {
    var myTextBox:TextField = new TextField();
    var myText:String = "Bytes loaded";
    function TextWithImage()
    addChild(myTextBox);
    myTextBox.text = myText+netStr.bytesLoaded;
    /*--------------< Videoyu Durdurma, Oynatma ve Başa
    Alma >------------------*/
    stage.addEventListener( KeyboardEvent.KEY_DOWN,
    keyPressHandler );
    function keyPressHandler( e:KeyboardEvent ):void {
    // if the spaceBar is pressed then toggle video play/pause
    if( e.charCode == 32 ) {
    netStr.togglePause();
    play_btn.addEventListener(MouseEvent.MOUSE_DOWN, playVideo);
    function playVideo(e:MouseEvent) {
    netStr.resume();
    removeEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler
    pause_btn.addEventListener(MouseEvent.MOUSE_DOWN,
    pauseVideo);
    function pauseVideo(e:MouseEvent) {
    netStr.pause();
    stop_btn.addEventListener(MouseEvent.MOUSE_DOWN, stopVideo);
    function stopVideo(e:MouseEvent) {
    netStr.pause();
    netStr.seek(0);
    fastforward_btn.addEventListener(MouseEvent.MOUSE_DOWN,doForward);
    function doForward(e:MouseEvent):void {
    var f:int = 1; //you can schange the skipping time here
    netStr.pause();
    netStr.seek(netStr.time + f);
    netStr.resume();
    rewind_btn.addEventListener(MouseEvent.MOUSE_DOWN,doRewind);
    function doRewind(e:MouseEvent):void{
    var x:int = 2;
    netStr.pause();
    netStr.seek(netStr.time - x);
    netStr.resume();
    fullscreen_btn.addEventListener(MouseEvent.MOUSE_DOWN,doFull);
    function doFull(e:MouseEvent):void{
    stage.displayState = StageDisplayState.FULL_SCREEN;
    /*--------------< Videoyu Durdurma, Oynatma ve Başa
    Alma / >------------------*/
    /*--------------< Video İçin Yükleme Bilgi
    Çubuğu >------------------*/
    var loaderBg:Sprite = new Sprite();
    loaderBg.graphics.beginFill(0xc78f8e);
    loaderBg.graphics.drawRect(205 , 378 , 430 , 5);
    loaderBg.graphics.endFill();
    addChild(loaderBg);
    this.addEventListener(Event.ENTER_FRAME, fileLoaded);
    var loaderBar:Sprite = new Sprite();
    addChild(loaderBar);
    function fileLoaded(e:Event) {
    var percent:Number = (netStr.bytesLoaded * 100 ) /
    netStr.bytesTotal;
    loaderBar.graphics.clear();
    loaderBar.graphics.beginFill(0xDE2C18);
    loaderBar.graphics.drawRect(205 , 378 , percent * 4.32 , 5);
    loaderBar.graphics.endFill();
    if (percent==100) {
    this.removeEventListener(Event.ENTER_FRAME, fileLoaded);
    /*--------------< Video İçin Yükleme Bilgi
    Çubuğu / >------------------*/
    /*--------------< Video Meta Bilgileri
    >------------------*/
    var metaObject:Object = new Object();
    netStr.client = metaObject;
    metaObject.onMetaData = getMetaInformation;
    var lengthOfVideo:Number = 0;
    function getMetaInformation(e:Object):void {
    lengthOfVideo = e.duration;
    trace("Genişlik :" + e.width);
    trace("Yükseklik :" + e.height);
    /*--------------< Video Meta Bilgileri /
    >------------------*/
    /*--------------< Videonun Durum Çubuğu
    >------------------*/
    //may cause problem part
    var GraphicsExample :Sprite = new Sprite();
    var size:uint = 10;
    var bgColor:uint = 0x999999;
    var borderColor:uint = 0x999999;
    var borderSize:uint = 0;
    var cornerRadius:uint = 9;
    var gutter:uint = 5;
    var dragBar:Sprite = new Sprite();
    var halfSize:uint = Math.round(size / 2);
    dragBar.graphics.beginFill(bgColor);
    dragBar.graphics.lineStyle(borderSize, borderColor);
    dragBar.graphics.drawCircle(halfSize, halfSize, halfSize);
    dragBar.graphics.endFill();
    dragBar.x=201;
    dragBar.y=376;
    addChild(dragBar);
    var drag:Boolean = false;
    this.addEventListener(Event.ENTER_FRAME, setDragBar);
    function setDragBar(e:Event) {
    if (!drag) {
    dragBar.x = ((netStr.time / lengthOfVideo) * 429) + 201;
    /*--------------< Videonun Durum Çubuğu /
    >------------------*/
    /*--------------< Videonun Kaydırma Çubuğu
    >------------------*/
    dragBar.addEventListener(MouseEvent.MOUSE_DOWN,
    startDragging);
    dragBar.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
    dragBar.buttonMode = true;
    var rect:Rectangle = new Rectangle(205,378,429,0);
    function startDragging(e:MouseEvent) {
    drag = true;
    netStr.pause();
    dragBar.startDrag(false,rect);
    function stopDragging(e:MouseEvent) {
    dragBar.stopDrag();
    drag = false;
    netStr.resume();
    this.addEventListener(Event.ENTER_FRAME, reSetVideo);
    function reSetVideo(e:Event) {
    if (drag) {
    netStr.seek(Math.floor(((dragBar.x-201) / 429) *
    lengthOfVideo ));
    /*--------------< Videonun Kaydırma Çubuğu
    / >------------------*/
    netStr.addEventListener(NetStatusEvent.NET_STATUS,
    netStatusHandler1);
    function netStatusHandler1(e:NetStatusEvent):void
    switch (e.info.code)
    case "NetStream.Seek.InvalidTime":
    trace("You have seeked too far ahead, the video hasn't fully
    loaded yet");
    break;
    case "NetStream.Play.StreamNotFound":
    trace("Unable to locate video");
    break;
    /*--------------< Video Ses Kontrolü
    >------------------*/
    sound_btn.addEventListener(MouseEvent.MOUSE_DOWN, setSound);
    var checkSound:Boolean = true;
    var soundTrans:SoundTransform = new SoundTransform();
    function setSound(e:MouseEvent) {
    if (checkSound) {
    soundTrans.volume = 0;
    checkSound = false;
    } else {
    soundTrans.volume = 1;
    checkSound =true;
    netStr.soundTransform = soundTrans;
    /*--------------< Video Ses Kontrolü /
    >------------------*/
    [/code]

  • Problems with startDrag()

    Has anyone else had problems with Sprite#startDrag() when
    using the optional parameters?
    According to the documentation, I should be able to compile
    something like:
    tile.startDrag( true, tile.parent.getBounds());
    This behavior is documented as:
    public function startDrag(lockCenter:Boolean = false,
    bounds:Rectangle = null):void
    where the first parameter says "center the sprite on the
    mouse" rather than where the use clicked and the second parameter
    constrains the movement of the sprite to the bounding box, measured
    in the Sprite's parent's coordinates.
    However, when I go to compile this, the first error I get is
    that Sprite#startDrag() only accepts one argument:
    mover.mxml(17): Error: Incorrect number of arguments.
    Expected 1.
    t.startDrag( false, t.parent.getBounds());
    Ooops...which one? It turns out it only takes the less useful
    one (lockCenter). However, when I try:
    tile.startDrag( true);
    I do not get the described behavior at all. Instead, the
    mouse is locked to 0,0 on the Sprite and the mouseUp will not work
    at all (the Sprite gets "stuck" to the mouse). If I go back to:
    tile.startDrag();
    everything works as expected but I still can drag the Sprite
    anywhere I want. This is not the desired behavior. Here is some
    code to test that this is the case on other systems, here:
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    width="600" height="400" creationComplete="init();">
    <mx:Script>
    <![CDATA[
    import flash.events.MouseEvent;
    public function init(): void {
    tile.addEventListener( MouseEvent.MOUSE_DOWN,
    handleMouseDown);
    tile.addEventListener( MouseEvent.MOUSE_UP, handleMouseUp);
    public function handleMouseDown( event: MouseEvent): void {
    var t : Canvas = Canvas( event.target);
    t.addEventListener( MouseEvent.MOUSE_MOVE, handleMouseMove);
    // t.startDrag( true); // the default is false
    t.startDrag( false, t.parent.getBounds());
    // t.startDrag();
    public function handleMouseUp( event: MouseEvent): void {
    var t : Canvas = Canvas( event.target);
    t.removeEventListener( MouseEvent.MOUSE_MOVE,
    handleMouseMove);
    t.stopDrag();
    public function handleMouseMove( event: MouseEvent): void {
    var t : Canvas = Canvas( event.target);
    event.updateAfterEvent();
    ]]>
    </mx:Script>
    <mx:Panel id="pallette" height="100%" width="100%"
    clipContent="true">
    <mx:Canvas id="tile" x="25" y="25" width="25" height="25"
    backgroundColor="red"/>
    </mx:Panel>
    </mx:Application>

    okay, duh. The problem is not that Sprite#dragStart() has the
    wrong number of arguments. getBounds() has the wrong number of
    arguments.
    Need better error reporting from the compiler...it should say
    which method was expecting 1 argument.

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Problem with threads running javaw

    Hi,
    Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
    troy.

    troy,
    Try and post a minimum code sample of your app which
    does not work.
    When using javaw, make sure you redirect the standard
    error and standard output streams to file.
    Graeme.Hi Graeme,
    I dont understand what you mean by redirection to file? some of my code below.
    The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
    public class Server{
    ServerSocket aServerSocket;
    Socket dianosticsSocket;
    Socket nPortExpress;
    ClientListener aClientListener;
    LinkedList queue = new LinkedList();
    int port = 0;
    int clientPort = 0;
    String clientName = null;
    boolean serverAlive = true;
    * Server constructor generates a server
    * Socket and then starts a client threads.
    * @param aPort      socket port of local machine.
    public Server(int aPort, String aClientName, int aClientPort){
    port = aPort;
    clientName = aClientName;
    clientPort = aClientPort;
    try{
    // create a new thread
    aServerSocket = new ServerSocket(port) ;
    // connect to the nPortExpress
    aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
    // aClientListener.setDaemon(true);
    aClientListener.start();
    // start a dianostic port
    DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
    // System.out.println("Server is running on port " + port + "...");
    // System.out.println("Connect to nPort");
    catch(Exception e)
    // System.out.println("ERROR: Server port " + port + " not available");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
    serverAlive = false;
    System.exit(1);
    while(serverAlive&&aClientListener.hostSocket.isConnected()){
    try{
    // connect the client
    Socket aClient = aServerSocket.accept();
    //System.out.println("open client connection");
    //System.out.println("client local: "+ aClient.getLocalAddress().toString());
    // System.out.println("client localport: "+ aClient.getLocalPort());
    // System.out.println("client : "+ aClient.getInetAddress().toString());
    // System.out.println("client port: "+ aClient.getLocalPort());
    // make a new client thread
    ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
    // start thread
    clientThread.start();
    catch(Exception e)
    //System.out.println("ERROR: Client connection failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
    }// end while
    } // end constructor Server
    void serverExit(){
         JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
         System.exit(1);
    }// end class Server
    *** connect to another server
    public class ClientListener extends Thread{
    InetAddress hostName;
    int hostPort;
    Socket hostSocket;
    BufferedReader in;
    PrintWriter out;
    boolean loggedIn;
    LinkedList queue;      // reference to Server queue
    Server serverRef; // reference to main server
    * ClientListener connects to the host server.
    * @param aHostName is the name of the host eg server name or IP address.
    * @param aHostPort is a port number of the host.
    * @param aLoginName is the users login name.
    public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer)      // reference to Server queue)
    hostName = aHostName;
    hostPort = aHostPort;
    queue = aQueue;
    serverRef = aServer;      
    // connect to the server
    try{
    hostSocket = new Socket(hostName, hostPort);
    catch(IOException e){
    //System.out.println("ERROR: Connection Host Failed");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);     
    System.exit(0);
    } // end constructor ClientListener
    ** multi client connection server
    ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
    queue = aQueue;
    addToQueue(this);
    client = aSocket;
    clientRef = aClientListener;
    aDiagnostic = diagnostics;
    } // end constructor ClientWorker
    * run method is the main loop of the server program
    * in change of handle new client connection as well
    * as handle all messages and errors.
    public void run(){
    boolean alive = true;
    String aSubString = "";
    in = null;
    out = null;
    loginName = "";
    loggedIn = false;
    while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
    if(aDiagnostic){
    out.println("WELCOME to diagnostics");
    broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    out.println("WELCOME to Troy's Server");
    broadCastDia("Connect : client "+client.getInetAddress().toString());
         out.flush();
    String line;
    while(((line = in.readLine())!= null)){
    StringTokenizer aStringToken = new StringTokenizer(line, " ");
    if(!aDiagnostic){
    broadCastDia(line);
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    else{
    if(line.equals("GETIPS"))
    getIPs();
    else{
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    } // end while
    catch(Exception e){
    // System.out.println("ERROR:Client Connection reset");
                             JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);     
    try{
    if(aDiagnostic){
    broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    broadCastDia("Disconnect : client "+client.getInetAddress().toString());
         out.flush();
    // close the buffers and connection;
    in.close();
    out.close();
    client.close();
    // System.out.println("out");
    // remove from list
    removeThreadQueue(this);
    alive = false;
    catch(Exception e){
    // System.out.println("ERROR: Client Connection reset failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);     
    }// end while
    } // end method run
    * method run - Generates io stream for communicating with the server and
    * starts the client gui. Run also parses the input commands from the server.
    public void run(){
    boolean alive = true;
    try{
    // begin to life the gui
    // aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
    // aGuiClient.show();
    in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
    while (alive && hostSocket.isConnected()){
    String line;
    while(((line = in.readLine())!= null)){
    System.out.println(line);
    broadCast(line);
    } // end while
    } // end while
    catch(Exception e){
    //     System.out.println("ERRORa Connection to host reset");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
    try{
    hostSocket.close();
         }catch(Exception a){
         JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
    alive = false;
    System.exit(1);
    } // end method run

  • Problem with threads and camera.

    Hi everybody!
    I've a problem with taking snapshot.
    I would like to display a loading screen after it take snapshot ( sometimes i
    have to wait few seconds after i took snapshot. Propably photo is being taken in time where i have to wait).
    I was trying to use threads but i didn't succeed.
    I made this code:
    display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while((!performing.isShown()) && (backgroundCamera.isShown())){
                        Thread.yield();
                    notifyAll();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        this.wait();                   
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();This code is sometimes showing performing screen but sometimes no.
    I don't know why. In my opinion performing.isShown() method isn't working correctly.
    Does anyone have some idea how to use threads here?

    Hi,
    I've finally managed to work this fine.
    The code:
           Object o = new Object();
           display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while(!performing.isShown()){
                        Thread.yield();
                   synchronized(o) {
                      o.notify();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        synchronized(o) {
                           o.wait(1);
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();

  • Problem with threads hanging

    We have a problem where our application stops responding after a few days of usage. Things will for fine for a day or two, and then pretty quickly threads will start getting hung up, usually in places where they are allocating memory
    We are running WebLogic 8.1 SP2 on Sun JDK 1.4.2_04 on Solaris 8 using the alternate threading model and the -server hotspot vm. We are running pretty much the same code that we had no problems with under WebLogic 6.1 SP4 and Sun JDK 1.3.1.
    A thread dump usually shows that some or all of our execute threads are in the state "waiting for monitor entry" even though they are not currently waiting on any java locks. Here is a sample thread from the thread dump (we have ~120 threads so I don't want to post the full dump).
    =============================================================================================
    "ExecuteThread: '8' for queue: 'itgCrmWarExecutionQueue'" daemon prio=5 tid=0x005941d0 nid=0x2c waiting for monitor entry [c807f000..c807fc28]
    at java.lang.String.substring(String.java:1446)
    at java.lang.String.substring(String.java:1411)
    at weblogic.servlet.internal.ServletRequestImpl.getRelativeUri(ServletRequestImpl.java:1872)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3492)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2585)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
    =============================================================================================
    String.java line 1446 for this jdk allocates a new String object, and all the other threads in this state also are creating new objects or arrays, etc.
    We've done a pstack on this process when it's in this state, and the threads that are in the "waiting for monitor entry" that look like they're allocating memory are all waiting on the same lwp_mutex_lock with some allocation method that's calling into the native TwoGenerationCollectorPolicy.mem_allocate_work (see pstack output below for the same thread as in the thread dump above)
    =============================================================================================
    ----------------- lwp# 44 / thread# 44 --------------------
    ff31f364 lwp_mutex_lock (e3d70)
    fee92384 __1cNObjectMonitorGenter26MpnGThread__v_ (5000, 525c, 5000, 50dc, 4800, 4af0) + 2d8
    fee324d4 __1cSObjectSynchronizerKfast_enter6FnGHandle_pnJBasicLock_pnGThread__v_ (c807f65c, c807f7d4, 5941d0, 0, 35d654, fee328ec) + 68
    fee32954 __1cQinstanceRefKlassZacquire_pending_list_lock6FpnJBasicLock__v_ (c807f7d4, ff170000, d4680000, 4491d4, fee1bc2c,
    0) + 78
    fee3167c __1cPVM_GC_OperationNdoit_prologue6M_i_ (c807f7bc, 4400, ff170000, 2d2b8, 4a6268, c807fa18) + 38
    fee2e0b0 __1cIVMThreadHexecute6FpnMVM_Operation__v_ (c807f7bc, 963a8, 0, 0, 1, 0) + 90
    fed2c2a4 __1cbCTwoGenerationCollectorPolicyRmem_allocate_work6MIii_pnIHeapWord__ (962c0, ff1c29ec, ff1c297c, ff131a26, 4800, 4998) + 160
    fed22940 __1cNinstanceKlassRallocate_instance6MpnGThread__pnPinstanceOopDesc__ (ee009020, 5941d0, 15ca581, 3647f0, 4a6268, c807f8c8) + 180
    fed34928 __1cLOptoRuntimeFnew_C6FpnMklassOopDesc_pnKJavaThread__v_ (ee009018, 5941d0, 0, 0, 0, 0) + 28
    fa435a58 ???????? (ee009018, e86de, 15ca4de, 50dc, 5941d0, c807f9c8)
    fb36f9a4 ???????? (0, d412ccd8, ee046c28, ff170000, 0, 0)
    fad8b278 ???????? (ee046c28, d6000c90, ee046530, 8, db8e8450, c807f9e8)
    fad62abc ???????? (d412ccd8, ee046530, d6000c90, ee3bfa38, 8, c807fa18)
    fa4b3c38 ???????? (c807fb9c, 0, f2134700, fa415e50, 8, c807faa8)
    fa40010c ???????? (c807fc28, c807fe90, a, ee9e1e20, 4, c807fb40)
    fed5d48c __1cJJavaCallsLcall_helper6FpnJJavaValue_pnMmethodHandle_pnRJavaCallArguments_pnGThread__v_ (c807fe88, c807fcf0, c807fda8, 5941d0, 5941d0, c807fd00) + 27c
    fee4b784 __1cJJavaCallsMcall_virtual6FpnJJavaValue_nLKlassHandle_nMsymbolHandle_4pnRJavaCallArguments_pnGThread__v_ (ff170000, 594778, c807fd9c, c807fd98, c807fda8, 5941d0) + 164
    fee5e8dc __1cJJavaCallsMcall_virtual6FpnJJavaValue_nGHandle_nLKlassHandle_nMsymbolHandle_5pnGThread__v_ (c807fe88, c807fe84, c807fe7c, c807fe74, c807fe6c, 5941d0) + 6c
    fee6fc74 __1cMthread_entry6FpnKJavaThread_pnGThread__v_ (5941d0, 5941d0, 838588, 594778, 306d10, fee69254) + 128
    fee6927c __1cKJavaThreadDrun6M_v_ (5941d0, 2c, 40, 0, 40, 0) + 284
    fee6575c _start   (5941d0, fa1a1600, 0, 0, 0, 0) + 134
    ff3758c0 lwpstart (0, 0, 0, 0, 0, 0)
    =============================================================================================
    Also when it's having this problem, the "VM Thread" is always using a lot of processor time. We did a couple of pstacks today while it was having this problem, and this thread was stuck in the ONMethodSweeper.sweep for over 15 minutes when we finally killed the server.
    From the thread dump:
    "VM Thread" prio=5 tid=0x000e2d20 nid=0x2 runnable
    From the first pstack:
    =============================================================================================
    ----------------- lwp# 2 / thread# 2 --------------------
    fed40c04 __1cXvirtual_call_RelocationIparse_ic6FrpnICodeBlob_rpC5rppnHoopDesc_pi_nNRelocIterator__ (42a2f4, fa5fa46d, ffffffff, fc4ffcb8, 42a2f4, 42a324) + 124
    fed46318 __1cKCompiledIC2t5B6MpnKRelocation__v_ (42a2f0, fc4ffd24, fc4ffd4c, e802, 0, 6) + 38
    fed90c38 __1cHnmethodVcleanup_inline_caches6M_v_ (fa5f7f88, fa608940, 1, 0, fa400000, 6) + 1ac
    fede18b4 __1cONMethodSweeperFsweep6F_v_ (2cf38, 0, ffffffff, ff1cf1fc, ff1c66e8, fede1d44) + 1b0
    fede1e6c __1cUSafepointSynchronizeFbegin6F_v_ (2cf38, ff1ba138, 5000, 50dc, 5000, 525c) + 248
    feef1fd4 __1cIVMThreadEloop6M_v_ (4400, 4000, 4324, 4000, 42b0, 3800) + 3d4
    feef1ae4 __1cIVMThreadDrun6M_v_ (e2d20, 2, 40, 0, 40, 0) + 8c
    fee6575c _start   (e2d20, ff270200, 0, 0, 0, 0) + 134
    ff3758c0 lwpstart (0, 0, 0, 0, 0, 0)
    =============================================================================================
    Second pstack
    =============================================================================================
    ----------------- lwp# 2 / thread# 2 --------------------
    fed41180 __1cXvirtual_call_RelocationIparse_ic6FrpnICodeBlob_rpC5rppnHoopDesc_pi_nNRelocIterator__ (0, ff1b9664, ffffffff, fc4ffcb8, a6f2cc, fc4ffbd0) + 6a0
    fed46318 __1cKCompiledIC2t5B6MpnKRelocation__v_ (a6f2c8, fc4ffd24, fc4ffd4c, e802, 0, 6) + 38
    fed90c38 __1cHnmethodVcleanup_inline_caches6M_v_ (faded4c8, fadf2c80, 1, 0, fa400000, 6) + 1ac
    fede18b4 __1cONMethodSweeperFsweep6F_v_ (2cf38, 0, ffffffff, ff1cf1fc, ff1c66e8, fede1d44) + 1b0
    fede1e6c __1cUSafepointSynchronizeFbegin6F_v_ (2cf38, ff1ba138, 5000, 50dc, 5000, 525c) + 248
    feef1fd4 __1cIVMThreadEloop6M_v_ (4400, 4000, 4324, 4000, 42b0, 3800) + 3d4
    feef1ae4 __1cIVMThreadDrun6M_v_ (e2d20, 2, 40, 0, 40, 0) + 8c
    fee6575c _start   (e2d20, ff270200, 0, 0, 0, 0) + 134
    ff3758c0 lwpstart (0, 0, 0, 0, 0, 0)
    =============================================================================================
    Has anyone ever seen anything like this? I'm trying to figure out if this is caused by something we're doing, or something relating to our environment and jvm options. Any ideas?

    Thanks for the reply - I'm testing our app with the +UseConcMarkSweepGC now in our test environment to make sure it doesn't cause any problems there.  Unfortunately the only place we've had this problem is on the production server, so it's extra difficult debugging this. 
    We're using the following memory options:
    -ms512m -mx512m -XX:NewSize=128m -XX:PermSize=192m -XX:MaxNewSize=128m -XX:MaxPermSize=192m -XX:SurvivorRatio=8and the following debugging options, as we've also been seeing OutOfMemoryErrors ( see http://forum.java.sun.com/thread.jsp?forum=37&thread=522354&tstart=45&trange=15 )
    -verbosegc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGCBTW, which c++filt version and options are you using? Our Solaris boxes only seem to have the GNU version installed. I was trying to run that on some of the other stack traces and wasn't getting anywhere, and didn't know if because it was GNU version wouldn't work on something compiled with the Sun compiler.
    Thanks!
    --Andy                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Problem with threads and ProgressMonitor

    Dear Friends:
    I have a little problem with a thread and a ProgressMonitor. I have a long time process that runs in a thread (the thread is in an separate class). The thread has a ProgressMonitor that works fine and shows the tasks progress.
    But I need deactivate the main class(the main class is the user interface) until the thread ends.
    I use something like this:
    LongTask myTask=new LongTask();
    myTask.start();
    myTask.join();
    Now, the main class waits for the task to end, but the progress monitor don`t works fine: it shows only the dialog but not the progress bar.
    What's wrong?

    Is the dialog a modal dialog? This can block other UI updates.
    In general, you should make sure that it isn't modal, and that your workThread has a fairly low priority so that the UI can do its updating

Maybe you are looking for

  • I can't get two "room" objects to "glue" together in a floor plan

    I can 't get two rooms to "glue" together in Visio 2010. I've tried several ways to drag the "room" objects and handles around the floor plan but not only do the rooms not glue to each other, they snap or glue to other things (like ruler divisions),

  • Technical competition team needs Labview Developer

    The KC Space Pirates are a team in NASAs Beamed power competition. We are looking into using Labview to automate aiming a high power laser. I am looking for an experienced Labview developer to help with the project. There is no pay if we don't win. I

  • GroupWise 8 + Outlook 2013 on the same PC (headaches)

    So I have a problem that's been making me pull my hair out and was hoping someone could offer some advice. OS - Windows 7 Professional x64 (all Windows Updates installed) GroupWise version - 8 I have a user (who is a local admin on that machine) who

  • Use of Persistence API

    Hi,           I want to know any business scenario, or any case where the Persistence API are explicitly needed.Whenever we use a smart sync application based on the metaRep.xml file the persistence to the DB2E or filesystem is taken care of by the F

  • Budget controlling for PO using internal order

    Dear experts , can anyone tell me the step by step procedure to have a budget controlling on PO based on budget ? Regards anis