Solved

Reload XML (Text, Images & Video) Data - Memory Leak

Posted on 2009-07-15
8
1,374 Views
Last Modified: 2013-11-12
I have an Flash AS3 application that will be used to display Text Based Events, Images and Video Clips.  This will be updateable from a web app that alters an xml feed.  The XML Feed will be reloaded on a set timer which will reload all the data into arrays.

I'm having memory leak issues with reloading image data from xml.  
As my movie continues to play, it continues to leak memory.  
If i don't keep recreating my image objects the application is fine but i need to reload (on a set time preferrably) as clients are going to be updating this throughout the day.

I have posted some code on how i'm loading/reloading the xml document, creating the images objects and displaying them.

Any help with this would be greatly appreciated as i'm getting desperate to fix my memory issue.  
//Get Latest XML Feed

public function getXMLData() {

    var xmlRequest:URLRequest = new URLRequest("items2.xml");

    var xmlLoader:URLLoader = new URLLoader();

    //Create an event listener to check when the XML load is complete

    xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded, false, 0, true);

    xmlLoader.load(xmlRequest);

}

 

//XML Has Loaded

function xmlLoaded(e:Event):void {

    trace("XML HAS RELOADED");

    mydata = XML(e.target.data);

    XML.ignoreWhitespace = true;

    feedisLoaded = 1;

    

    this.ParseImages();

}

 

//Create Image Objects and Add to Array

function ParseImages():void {

    trace("IN CREATE IMAGES ");

    for(i=0;i < mydata.galleries.gallery.length();i++)

    {

        myImg = new ImageItem();

        myImg.imageURL = mydata.galleries.gallery[i].image;

        displayArray.push(myImg);

    }

    imgTimer.addEventListener(TimerEvent.TIMER, displayImages, false, 0, true);

    imgTimer.start();

}

 

/**************************** DISPLAY ROUTINES *******************************************/

function displayImages(e:Event):void {

    trace("Image POSITION " + imgPosition + " Display Array Length " + displayArray.length);

    if (imgPosition == displayArray.length)

    {

        imgTimer.stop();

        imgTimer.removeEventListener(TimerEvent.TIMER, displayImages);

        imgPosition = 0;

        //Clear Array

        displayArray = [];

        

        //Reload XML Feed

        trace("RELOADING XML!!!!");

        getXMLData();

    } else

    {

        var imageLoader:Loader = new Loader();

        addChild(imageLoader);

        imageLoader.load(new URLRequest(displayArray[imgPosition].imageURL));

        imgView.addChild(imageLoader);

        trace("Display Images -> Memory Useage DI END: " + System.totalMemory/1024 +" Kb");

        imgPosition++;

    }

}

Open in new window

0
Comment
Question by:Adam409
  • 4
  • 3
8 Comments
 
LVL 9

Expert Comment

by:danyul_c
ID: 24864650
If you're loading new ones over the top of the existing ones. Try delete them before calling instantiating the new ones. Delete each image and delete the arrays.

delete displayArray;
displayArray = [];

Then when flash player next runs its garbage collection the memory allocated to these objects should be freed up.
0
 

Author Comment

by:Adam409
ID: 24864692
Hi Danyul,

When i try and delete the Array i get an error
1189: Attempt to delete the fixed property displayArray.  Only dynamically defined properties can be deleted.

Now if i'm deleting the array do i need to remove everything from it first or can i delete the array and the garbage collector will remove all objects that were contained within it?

Also i'm curious if i'm handling the Loader objects, Listeners and Timer objects efficiently.

Thanks again for your help.
Adam
0
 
LVL 9

Expert Comment

by:danyul_c
ID: 24864968
I'm a little confused as to the order you are trying to complete each task.

If you let me know which order you want the get xml, have the timer interval, etc.

If you let me know that I can do a quick summary of how to do it.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:Adam409
ID: 24865815
Thanks again Danyul for the quick response.

Here's the order i'm doing things.
Start Program
Grab XML Document
Read XML Document
Start Timer to Reload XML Document
Load Event Objects into DisplayArray
Load Image Objects into DisplayArray
Load Video Objects into Display Array
Loop Through DisplayArray adding items to stage / display containers
Keep looping till XML Timer says to Reload XML Document and do everything all over again

If possible would you have some example code on how i could do this?? That would be awesome!

Thanks in advance.
0
 
LVL 9

Expert Comment

by:danyul_c
ID: 24866334
I do mostly use Flex so forgive me if some of this is a little excessive.

I've created a basic class which to can cannibalize to suit your needs, it has the required timers and performs actions in the order you have specified.

I have left out excessive references to try avoid the memory leaks you have been seeing. Keep in mind though Flash Players garbage collection is one odd puppy, it seems to operate heuristically and only on assignment of new data. And it will only clean up object that have no references left. This is why I have tried to keep refs at a minimum but give you the functionality you need.

You will probably need to change the part where the items are added to the stage to suit your needs.
package

{

	import flash.display.Sprite;

	import flash.events.Event;

	import flash.events.TimerEvent;

	import flash.net.URLLoader;

	import flash.net.URLRequest;

	import flash.utils.Timer;

	

	public class LoaderMagig extends Sprite

	{

		private var _currentItem:int;

		private var _cycleTimer:Timer;

		private var _displayArray:Array;

		private var _displayItem:Sprite;

		private var _refreshTimer:Timer;

		

		public function LoaderMagig()

		{

			XML.ignoreWhitespace = true;

			

			_currentItem = -1;

			

			_displayItem = new Sprite();

			addChild(_displayItem);

			

			_cycleTimer = new Timer(1000);

			_cycleTimer.addEventListener(TimerEvent.TIMER, _cycleItems);

			

			_refreshTimer = new Timer(10000, 1);

			_refreshTimer.addEventListener(TimerEvent.TIMER, _refreshItems);

			

			_getXml();

		}

		

		private function _cycleItems(e:TimerEvent):void

		{

			if (_displayArray.length > 0) {

				while (_displayItem.numChildren > 0) {

					_displayItem.removeChildAt(0);

				}

				

				_currentItem++;

				

				if (_currentItem >= _displayArray.length) {

					_currentItem = 0;

				}

				

				_displayItem.addChild(_displayArray[_currentItem]);

			}

		}

		

		private function _getXml():void

		{

			var urlRequest:URLRequest = new URLRequest('items2.xml');

			var urlLoader:URLLoader = new URLLoader();

			urlLoader.addEventListener(Event.COMPLETE, _getXmlHandler);

			urlLoader.load(urlRequest);

		}

		

		private function _getXmlHandler(e:Event):void

		{

			var xmlData:XML = XML(e.currentTarget.data);

			_cycleTimer.stop();

			_currentItem = -1;

			_displayArray = [];

			

			for (var i:int = 0; i < xmlData.galleries.gallery.length(); i++) {

				_displayArray.push(new URLLoader(new URLRequest(xmlData.galleries.gallery[i].image)));

			}

			

			_cycleTimer.start();

			_refreshTimer.start();

		}

		

		private function _refreshItems(e:TimerEvent):void

		{

			_refreshTimer.reset();

			_getXml();

		}
 

	}

}

Open in new window

0
 

Author Comment

by:Adam409
ID: 24886349
Hey Danyul,

Thanks again for helping and sorry for not getting back to you right away on this.  I finally had a chance to test your solution and i seem to get an error when it tries to display the image.

TypeError: Error #1034: Type Coercion failed: cannot convert flash.net::URLLoader@2d3c551 to flash.display.DisplayObject.

Adam
0
 
LVL 9

Accepted Solution

by:
danyul_c earned 500 total points
ID: 24999463
Ok what you're going to have to do is determine what type of object you are loading each time (possibly by the extension) and then, for a bitmap eg.

for text events you should be able to add "_displayArray[_currentItem].data as String" to a textfield.text. The video clip is the only thing i'm not sure about.
var newBitmap:Bitmap = new Bitmap(BitmapData(_displayArray[_currentItem].data));

_displayItem.addChild(newBitmap);

Open in new window

0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

I have been doing hardcore actionscripting for some time; and needless to say I have faced a lot of problems in just understanding others' code rather than understanding what the code executes. A programmer's life can become hell when there are a lo…
In my long career of working as an actionscript developer, I had spent sleepless night often working hard to solve some small problems which actually took a lot of my development time; later found out the solutions to be a line or two. Here are s…
The purpose of this video is to demonstrate how to Test the speed of a WordPress Website. Site Speed is an important metric of a site’s health. Slow site speed can result in viewers leaving your site quickly and not seeing your content. This…
The purpose of this video is to demonstrate how to update a WordPress Site’s version. WordPress releases new versions of its software frequently and it is important to update frequently in order to keep your site secure, and to get new WordPress…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now