How to add sprite to a body in Box2D in Adobe AIR, FLEX and FLASH? Or Add image/Sprite to a body in ActionScript.

The below code is for FlashBuilder 4, If you are using FlexBuilder3 use addChild()
instead of the commented block in the following code.

public function addCircle(){x:Number, y: Number, radius:Number, ballcip:Ball):void{

bd:b2BodyDef = new b2BodyDef();

      var loader:Loader = new Loader();

      loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,
                                                           imageFailed);
      var request:URLRequest = new URLRequest("ball.png");
      loader.load(request);

      /*optionally change the position of the image if not fitting in the body */
      /* You can also rotate the image.*/
      loader.x = -50;
      loader.y = -50;

      /***************************************/
      var ui:UIComponent = new UIComponent();
      ui.addChild(loader);
      this.addElement(ui);
      /**************************************/

      bd.userData = ui;
      bd.position.Set(_x/m_phys_scale, _y/ m_phys_scale);
      bd.type=b2Body.b2_dynamicBody;
      var ball_shape:b2CircleShape=new b2CircleShape(50/world_scale);
      var ball_fixture:b2FixtureDef = new b2FixtureDef();
      ball_fixture.shape=ball_shape;
      ball_fixture.friction=0.9;
      ball_fixture.density=30;
      ball_fixture.restitution=0.3;
      ball_body=world.CreateBody(bd);
      ball_body.CreateFixture(ball_fixture);
}

private function imageFailed(event:IOErrorEvent):void
{
      Alert.show("Image loading failed"); //make sure you have the image.
}

Load a webpage in Adobe AIR

This example shows how to load a webpage inside Adobe AIR,
For this first you have to place an HTML control in your design for loading the html content.
Create an page “index.html” inside the application directory of your current project and add some Html content to it.
After that copy the following code to your source file.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="init()">
<mx:Script>
<![CDATA[
      private function init():void
      {
         this.stage.nativeWindow.maximize();    // maximizes your window.
         html.location="index.html";            // loads the html content in the html text area.
      }
]]>
</mx:Script>
<mx:HTML id="html"     width="100%" height="100%" />
</mx:WindowedApplication>

Please leave your comments on this post…….

Using ButtonBar in Adobe AIR/FLEX, A simple Example

Hello……….

A button Bar is a convenient way to place your buttons in an application. It saves a lots of space in your application interface.
Take a look at the following example which shows how to use the ButtonBar. An itemClickEvent is attached to each button in the ButtonBar.
You can place as many buttons inside a button Bar.
Copy the following code to your MXML file and you are done…….
Happy Coding………..

<?xml version="1.0"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" >
    <mx:Script>
        <![CDATA[
            import mx.events.ItemClickEvent;

            private function clickHandler(event:ItemClickEvent):void {
                    myTA.text="Selected button index: " +
                    String(event.index) + "n" +
                    "Selected button label: " +
                    event.label;
            }
        ]]>
    </mx:Script>

    <mx:ToggleButtonBar  borderStyle="solid"  horizontalGap="5"  itemClick="clickHandler(event);"
    	    toggleOnClick="true"  selectedIndex="-1">
        <mx:dataProvider>
            <mx:String>Button1</mx:String>
            <mx:String>Button2</mx:String>
            <mx:String>Button3</mx:String>
            <mx:String>Button4</mx:String>
        </mx:dataProvider>
    </mx:ToggleButtonBar>
    <mx:TextArea id="myTA" width="250" height="100"/>
</mx:WindowedApplication>

Please leave your comments on this post.

Toggle between Full Screen and normal Screen in Adobe AIR or FLEX.

Hi all………

We often need to toggle between fullscreen and normal screen in our application.
The following code snippet helps you to toggle between these two screens in Adobe AIR or Flex.
Here I am using StageDisplayState class to do both which has “stage.displayState = StageDisplayState.FULL_SCREEN” and ” stage.displayState = StageDisplayState.NORMAL” constants to do this.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"  applicationComplete="toggleScreen()">
       <mx:Script>
               <![CDATA[
                       import flash.display.StageDisplayState;
                       private function toggleScreen():void{
                               if(fullScreen.selected == true){
                                       this.goFullScreen();
                               } else {
                                       this.exitFullScreen();
                               }
                       }
                       private function goFullScreen():void {
                               stage.displayState = StageDisplayState.FULL_SCREEN;
                       }
                       private function exitFullScreen():void {
                               stage.displayState = StageDisplayState.NORMAL;
                       }
               ]]>
       </mx:Script>
       <mx:CheckBox label="Full Screen" id="fullScreen" click="this.toggleScreen()"
               	               selected="true"  horizontalCenter="0" verticalCenter="0"/>
</mx:WindowedApplication>
 

Programmatically change background in Adobe AIR/FLEX.

  private function change():void
   {
	this.setStyle("backgroundColor","#00FF00");
	this.setStyle("color","green");
   }
 

Create PopUp Window in Adobe AIR / FLEX, A simple Example.

Below code shows how to create a new popUp window in Adobe AIR or FLEX.
To create a new window “right click on the src folder and create a new MXML Component named Here “MyLoginForm” It should be aTitleWindow for the example below.
How ever You can create other components, but the code accordingly must change.

          import mx.managers.PopUpManager;
          import mx.core.IFlexDisplayObject;
          import myComponents.MyLoginForm;


          // Additional import statement to use the TitleWindow container.
          import mx.containers.TitleWindow;


          private function showLogin():void {
            // Create the TitleWindow container.
            var helpWindow:TitleWindow =
          TitleWindow(PopUpManager.createPopUp(this, MyLoginForm, false));


            // Add title to the title bar.
            helpWindow.title="Enter Login Information";


            // Make title bar slightly transparent.
            helpWindow.setStyle("borderAlpha", 0.9);


            // Add a close button.
            // To close the container, your must also handle the close event.
            helpWindow.showCloseButton=true;
          }
        ]]>
    

FullScreen Event in Adobe AIR or FLEX

 

The following simple code snippet explains how to get an eventListener for FullScreen Event in Adobe AIR or FLEX. The function “onScreenModeChange ” gets called when you maximizes your window.
private function init():void {
stage.addEventListener( FullScreenEvent.FULL_SCREEN, onEnteringFullScreenMode);
}
private function onEnteringFullScreenMode( e:FullScreenEvent ):void {
if( e.fullScreen ) {
// Do something on fullscreen……………
} else {
// Do something else………..
}
}

Please leave your valuable comments if this post was useful…..

How to remove an item in a row in Datagrid in Adobe AIR or FLEX?

Most often you may need to delete data from a datagrid in your application.
The code below shows one of the ways in which you can delete the corresponding row in your application.
Here I am placing a button in the datagrid for deleting and on its click I am getting the index of the datagrid, thus identifying the row.
Then by using

DataProvider.removeItemAt(DataGrid.selectedIndex);

I removed the row from it.
After that I am just refreshing the data in the Datagrid.
See the example below.

<?xml version=”1.0″ ?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”>
<mx:Script>
<![CDATA[
import mx.controls.DataGrid;
import mx.collections.XMLListCollection;
private var my_xml:XML =   <data>
<item1>data1</item1>
<item2>data2</item2>
<item3>data3</item3>
</data>;
[Bindable] private var DataProvider:XMLListCollection = new XMLListCollection(my_xm..item1);
public function deleteItem(event:MouseEvent):void{
DataProvider.removeItemAt(DataGrid.selectedIndex);
DataProvider.refresh();
}
]]>
</mx:Script>
<mx:DataGrid id=”DataGrid” dataProvider=”{DataProvider}”>
<mx:columns>
<mx:DataGridColumn headerText=”  Text “
dataField=”item”>
<mx:itemRenderer>
<mx:Component>
<mx:Text text=”{data}”/>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
<mx:DataGridColumn headerText=”Delete this Row”>
<mx:itemRenderer>
<mx:Component>
<mx:LinkButton label=”Delete”
click=”outerDocument.deleteItem(event)”/>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
</mx:Application>

Please post your comments on this post.

How to dynamically add controls in Adobe AIR or Flex?

Below example shows how to add a label control dynamically in AIR or FLEX.

var L : Label = new Label();
L.addEventListener(MouseEvent.CLICK,LabelListener);
L.name = “my_label_name”;
L.text = “my Text”;
addChild(L);

// This function listens to the mouse click in the above added label.
private function LabelListener(event:MouseEvent):void
{
}

Please note that you can add any control by this method.
You can also add any controls inside a container like VBox by this method.
The above code works for only Flex SDK 3 for working in Flash builder or SDK 4 or above you need to change the above code like this.

var ui:UIComponent = new UIComponent();
ui.addChild(L);
this.addElement(ui);

Access a remote database from Adobe AIR or FLEX.

Access a remote database from Adobe AIR or FLEX.

Many often you need to access online database from your application. For doing it in Adobe AIR of FLEX you need HttpService.
The following example shows how to access an online database from an AIR Application.
Note that you cannot return an array from a remote file or database, because the request is an asynchronous request. You can have a string as comma separated or some other separated which can be then send to our application. You can then split the string in your application according to your need.

Look at the example below which shows how to do this.

xmlns:mx="http://www.adobe.com/2006/mxml"
                  layout="absolute" applicationComplete="init()">
id="sender" url="http://localhost/testDB/index.php"
method="POST" resultFormat="text" result="resultHandler()" >
xmlns="">
                 { "ID"  }
import mx.utils.StringUtil;
import mx.rpc.events.FaultEvent;
import mx.controls.Alert;
public var result:String = "";

public function init():void{

      sender.addEventListener(FaultEvent.FAULT,errorOccurred);
      sender.send();          //sending request to php file.

}
public function errorOccurred(event:FaultEvent):void{
      trace('Invalid request');
      Alert.show('Invalid request');
}
public function resultHandler():void{

      result  = sender.lastResult.toString();  //get the result here from php as a string.
      trace(result);
      var arr : Array = new Array();

      arr = result.split("||",result.length);
      arr.pop();                                // remove the last blank element.....

      for(var i : int = 0; i < arr.length; i++){
            trace(arr[i]);
      }
}
]]>

The php part is given below

 $con = mysql_connect("localhost","root","");
if (!$con)
{
	die('Could not connect: ' . mysql_error());
}
mysql_select_db("testDB", $con);
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
      echo $row['user_id']."||";
}
mysql_close($con);

Crop an Image in Adobe AIR or Flex.

Below code shows how to crop an image in Adobe AIR. Change the mx:WindowedApplication to mx: Application to run it as a FLEX Application.

The code uses copyPixels to extract the desired part from the image file.

The important line in the below code crops the image.
cropBD.copyPixels(loadBD, new Rectangle(startPoint.x, startPoint.y, squareSize, squareSize),posPoint);



    
        

    
    
    

    
    

    
    

    
    


Using StyleManager in Adobe AIR and FLEX.

StyleManager can be used to change the theme of any control in Adobe AIR and Flex.
The code shows how to sue StyleManager and dynamically change the theme of your window and others.




HBox{
 backgroundColor: #ffffff;
}


	

		

Dynamically change the background of a window in Adobe AIR?

Change the background of your window with your selected image.
Copy and paste the following code to your AIR file and view the result.

Note: Please make sure that you have an image in your application source folder.
Here the image name is “image.jpg” else you will get URL not found error.

xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"  creationComplete="onCreationComplete(event)" height="800" width="800" >



            import mx.events.FlexEvent;

            private var bgLoader : Loader;
            private var bgBitmapData : BitmapData;
// set your require background image path
            private var bgImagePath:String = "image.jpg";

/************************************************************************
backgroundImage="assets/myimage.jpg" height="800" width="800" >
</mx:WindowedApplication>
backgroundImage="assets/myimage.jpg" will set as a background Image.
************************************************************************/

            private function onCreationComplete(event:FlexEvent):void
            {
                bgLoader = new Loader ();
                bgLoader.contentLoaderInfo.addEventListener (Event.COMPLETE, bgLoadingComplete, false, 0, true);
  &nbs p;             bgLoader.load (new URLRequest (bgImagePath));
            }
            private function bgLoadingComplete (event:Event):void
            {
                bgBitmapData = new BitmapData (bgLoader.width, bgLoader.height);
                bgBitmapData.draw ( bgLoader );

                bgCanvas.graphics.beginBitmapFill (bgBitmapData);
                bgCanvas.graphics.drawRect (0, 0, stage.stageWidth, stage.stageHeight);
                bgCanvas.graphics.endFill ();
            }

        ]]>


    id="bgCanvas" height="100%" width="100%" />

Pass a variable from one window to another in Adobe AIR?

We often need to access another window variable in the current window.
The following example shows how to access a variable from one window in the next window.
The logic is to create an object of next window in the current window and assign the value of variable in the current window itself so that it becomes available in the net window.
Take a look at the example.

/*********** passVar.mxml *********************/

xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">


                  import mx.core.Window;

                  private function init():void
                  {
                        var myWindow : win = new win();
                        myWindow.myVar = "Hello";
                        myWindow.open();
                  }
            ]]>

      x="106" y="134" label="Button" click="init()"/>

/********************************************************************************
 win.mxml -> This file’s object is created in the first file. So please give the exact name, it’s case sensitive also.  Take a look at the line in passVar.mxml
              var myWindow : win = new win();
*********************************************************************************/

xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="400" height="300" creationComplete="init2()">


                  import mx.controls.Alert;

                  public var myVar : String = "";

                  private function init2():void
                  {
                        Alert.show(myVar,"Passed Variable",4,this);
                  }
            ]]>

Create a polygon in Flash or Adobe AIR using Box2D.

The below function creates a polygon in the shape of a triangle.
Please call the debugdraw function inside your update method to view the results.
Make sure you import the Box2D classes into your file.

public function init():void
{
	 debug_draw();
	 addEventListener(Event.ENTER_FRAME, update);
	 createTriangle();
}


 public function createTriangle():void
 {
	 var fd : b2FixtureDef = new b2FixtureDef();
	 var initVel : b2Vec2 = new b2Vec2();
	 var bodyDef:b2BodyDef= new b2BodyDef();
	 var shape : b2PolygonShape = new b2PolygonShape();
	 bodyDef.type = b2Body.b2_dynamicBody;
	 bodyDef.position.Set(4.446215, 3.649402);
	 bodyDef.angle = 0.000000;
	 var polygon1 : b2Body = world.CreateBody(bodyDef);
	 initVel.Set(0.000000, 0.000000);
	 polygon1.SetLinearVelocity(initVel);
	 polygon1.SetAngularVelocity(0.000000);

	 var arr : Vector. = new Vector.();
	 arr[0] = new b2Vec2(-0.980080, 2.374502);
	 arr[1] = new b2Vec2(-0.980080, -1.187251);
	 arr[2] = new b2Vec2(1.960159, -1.187251);
	 shape.SetAsVector(arr,3);
	 fd.shape = shape;
	 fd.density = 0.30;
	 fd.friction = 0.300000;
	 fd.restitution = 0.600000;
	 fd.filter.groupIndex = 0;
	 fd.filter.categoryBits = 65535;
	 fd.filter.maskBits = 65535;
	 polygon1.CreateFixture(fd);
}


public function debug_draw():void
{
	 var debug_draw:b2DebugDraw = new b2DebugDraw();
	 var debug_sprite:Sprite = new Sprite();

	 /** Use this instead of addChild() ********/

	 var ui:UIComponent = new UIComponent();
	 ui.addChild(debug_sprite);
	 this.addElement(ui);

	 /*****************************************/
	 //addChild(debug_sprite);
	 debug_draw.SetSprite(debug_sprite);
	 debug_draw.SetDrawScale(world_scale);
	 debug_draw.SetFlags(b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit);
	 debug_draw.SetFillAlpha(0.5);
	 world.SetDebugDraw(debug_draw);
}

public function update(e:Event) : void
{
	 //We need to do this to simulate physics

	 world.Step(m_timestep,m_iterations,10);
	 for (var bb:b2Body=world.GetBodyList(); bb; bb=bb.GetNext())
	 {
		 if (bb.GetUserData() is Sprite)
		 {
			 bb.GetUserData().x=bb.GetPosition().x * 30;
			 bb.GetUserData().y=bb.GetPosition().y * 30;
			 bb.GetUserData().rotation=bb.GetAngle() * 180 / Math.PI;
		 }
	 }
	 world.DrawDebugData();
}

How to Implement Box2D in Adobe AIR?

Everyone will be fascinated how flash games are built on the web that implements the real world physics. Well for your information there are a lot of physics engines available.
One of them is the Box2D. Box2D was written in C++. Then it was converted to flash.

So now I am going to show you how to build these games on your desktop.
For this you need the Adobe Flashbuilder 4.
Download it from here http://www.adobe.com/products/flashbuilder/
And follow these steps.

1. First you have to download the Box2D library for flash.
2. Create a Flex Project for the desktop(i.e for Adobe AIR) and name it “Test”.
3. Create a folder named libs inside the project folder.
4. Right click on the libs and import the downloaded Box2D swc into it.
Or Right click on the project folder and click properties, add swc folder named libs which
contains your Box2D library for flash. After that a folde named “Referenced Libraries” will
appear.
See the figure below.

Now right click on the project folder and new-> Actionscript class-> name it “Ball” and press enter. A file named Ball.as will be created. Now copy the following code to this file.

/************************************** Ball.as ***********************************/

package
{
 import flash.display.Sprite;
 import flash.geom.Matrix;
 import mx.controls.Alert;

 public class Ball extends Sprite
 {
 private var mc:Sprite;
 public function Ball(radius:Number, color:Number = 0x660033)
 {
 super();
 mc = new Sprite();
 setRegistrationPoint( mc, mc.width >> 1, mc.height >> 1, true);
 mc.graphics.lineStyle(1, 0x000000);
 mc.graphics.beginFill(color);
 mc.graphics.drawCircle(0, 0, radius);
 mc.graphics.endFill();

 addChild(mc);
 }
 public function setRegistrationPoint(s:Sprite, regx:Number, regy:Number, showRegistration:Boolean) : void
 {
 s.transform.matrix = new Matrix(1, 0, 0, 1, -regx, -regy);
 if (showRegistration)
 {
 var mark:Sprite = new Sprite();
 mark.graphics.lineStyle(1, 0x000000);
 mark.graphics.moveTo(-5, -5);
 mark.graphics.lineTo(5, 5);
 mark.graphics.moveTo(-5, 5);
 mark.graphics.lineTo(5, -5);
 s.addChild(mark);
 }
 }
 }
}

Now copy the below code to Test.MXML

    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="init()">


   import mx.controls.Alert;
   import mx.core.UIComponent;
   import flash.display.Sprite;
   import flash.events.Event;
   import flash.events.MouseEvent;
   import flash.display.Stage;
   import Box2D.Dynamics.*;
   import Box2D.Collision.*;
   import Box2D.Collision.Shapes.*;
   import Box2D.Common.Math.*;

   public var the_ball:Ball;
   public var main:Main;
   public var m_dbgSprite:Sprite;
   public var m_world:b2World;
   public var m_phys_scale:Number = 30;
   public var m_timestep:Number = 1.0/30.0;
   public var m_iterations:N umber = 10.0;

   //initial box coordinates when we first press mouse down
   public var initX:Number = 0.0;
   public var initY:Number = 0.0;
   public var drawing:Boolean = false;
   public var b:b2Body;
   private var colorArray:Array = new Array(0xFFFF33, 0xFFFFFF, 0x79DCF4, 0xFF3333, 0xFFCC33, 0x99CC33);

   public function init():void{

    var gravity:b2Vec2 = new b2Vec2(0,9.8);
    var worldAABB:b2AABB = new b2AABB();
    worldAABB.lowerBound.Set(-1000,-1000);
    worldAABB.upperBound.Set(1000,1000);
    m_world = new b2World(worldAABB,gravity,true);

    //Add our ground and walls
    addStaticBox(250/m_phys_scale,510/m_phys_scale,250/m_phys_scale,10/m_phys_scale);
    addStaticBox(250/m_phys_scale,-10/m_phys_scale,250/m_phys_scale,10/m_phys_scale);
    addStaticBox(-10/m_phys_scale,250/m_phys_scale,10/m_phys_scale,250/m_phys_scale);
    addStaticBox(510/m_phys_scale,250/m_phys_scale,10/m_phys_scale,250/m_phys_scale);

    addEventListener(Event.ENTER_FRAME, update);
    stage.addEventListener(MouseEvent.MOUSE_DOWN,mousePressed);
    stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
    stage.addEventListener(MouseEvent.MOUSE_UP,mouseReleased);

    var dbgDraw:b2DebugDraw = new b2DebugDraw();
    var dbgSprite:Sprite = new Sprite();
    var ui:UIComponent = new UIComponent();
    ui.addChild(dbgSprite);
    this.addElement(ui);
    //addChild(dbgSprite);
    dbgDraw.m_sprite = dbgSprite;
    dbgDraw.m_drawScale = 20.0;
    dbgDraw.m_fillAlpha = 0.0;
    dbgDraw.m_lineThickness = 1.0;
    //dbgDraw.m_drawFlags = 0xFFFFFFFF;
    //dbgDraw.m_drawFlags=b2DebugDraw.e_shapeBit|b2DebugDraw.e_jointBit|b2DebugDraw.e_coreShapeBit|b2DebugDraw.e_aabbBit|b2DebugDraw.e_obbBit|b2DebugDraw.e_pairBit|b2DebugDraw.e_centerOfMassBit;

    m_world.SetDebugDraw(dbgDraw);
   }
   public function mousePressed(e:MouseEvent) : void {
    //Store initial X and Y position
    initX = e.localX;
    initY = e.localY;

    var randomColorId:Number = Math.floor(Math.random()*colorArray.length);

    the_ball = new Ball(50, colorArray[randomColorId]);

    the_ball.x = mouseX;
    the_ball.y = mouseY;
    the_ball.width = 1;
    the_ball.height = 1;
    var ui:UIComponent = new UIComponent();
    ui.addChild(the_ball);
    this.addElement(ui);

    drawing = true;
   }
   public function mouseMoved(e:MouseEvent) : void {
    if (drawing) {
     the_ball.x = mouseX;
     the_ball.y = mouseY;
    }
   }
   public function mouseReleased(e:MouseEvent) : void {
    drawing = false;
    addCircle( mouseX,  mouseY, the_ball.width/2,the_ball);
   }
   public function addCircle(_x:Number, _y:Number, _radius:Number, ballclip:Ball) : void {
    var bd:b2BodyDef = new b2BodyDef();
    var cd:b2CircleDef = new b2CircleDef();
    var area:Number = Math.floor(_radius*_radius*Math.PI/25)/100;

    cd.radius = Math.abs(_ra dius)/m_phys_scale;
    cd.density = 2;
    cd.restitution = 0.7;
    cd.friction = 2;
    bd.position.Set(_x/m_phys_scale, _y/ m_phys_scale);
    bd.userData = ballclip;
    b = m_world.CreateBody(bd);
    b.CreateShape(cd);
    b.SetMassFromShapes();
   }
   public function addStaticBox(_x:Number,_y:Number,_halfwidth:Number,_halfheight:Number) : void {
    var bodyDef:b2BodyDef = new b2BodyDef();
    bodyDef.position.Set(_x,_y);
    var boxDef:b2PolygonDef = new b2PolygonDef();
    boxDef.SetAsBox(_halfwidth,_halfheight);
    boxDef.density = 0.0;
    var body:b2Body = m_world.CreateBody(bodyDef);
    body.CreateShape(boxDef);
    body.SetMassFromShapes();
   }
   public function update(e:Event) : void {
    //We need to do this to simulate physics
    if (drawing) {
     the_ball.width+=2;
     the_ball.height+= 2;
    }
    m_world.Step(m_timestep,m_iterations);
    for (var bb:b2Body=m_world.m_bodyList; bb; bb=bb.m_next) {
     if (bb.m_userData is Sprite) {
      bb.m_userData.x=bb.GetPosition().x * 30;
      bb.m_userData.y=bb.GetPosition().y * 30;
      bb.m_userData.rotation=bb.GetAngle() * 180 / Math.PI;
     }
    }
   }
  ]]>
 

If you have errors that you can’t find in your file then go to window-> problems. Look for the problem.
If the problem is about the SDK . then right click on the project folder and properties and change the default SDK to FLEX 4.

How to read and write an XML file in Adobe AIR or Flex?

AIR treats the XML files as just as normal file and so you can proceed using the FileStream classs. Please take a look at the sample code. Just copy and paste the following code to your main.MXML file and you are done.

  import flash.xml.XMLDocument;

  private function init():void
  {
   xmlTA.text = " Sample XML ";
   var fileStream:FileStream = new FileStream();
   var prefsXML:XML =
           Sample
           XML
        ;

   var file:File = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream = new FileStream();
   fileStream.open(file, FileMode.WRITE);

   var outputString:String = 'n';
   outputString += prefsXML.toXMLString();

   fileStream.writeUTFBytes(outputString);
   fileStream.close();

   /* Reading the XML File */
   file = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream.open(file, FileMode.READ);
   prefsXML= XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
   readTA.text = prefsXML;
   fileStream.close();

   /*
    The previous examples use FileStream objects opened for synchronous operation.
    You can also open files for asynchronous operations (which rely on event listener functions to respond to events).
    For example, the following code shows how to read an XML file asynchronously:
   */

   file = File.applicationStorageDirectory.resolvePath("preferences.xml");
   fileStream = new FileStream();
   fileStream.addEventListener(Event.COMPLETE, processXMLData);
   fileStream.openAsync(file, FileMode.READ);

   function processXMLData(event:Event):void
   {
       prefsXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
       asyXML.text = prefsXML;
       fileStream.close();
   }

  }
 ]]>

Please post your comments on this post

Add Context menu in Adobe AIR or FLEX.

This sample shows how to add a menu to your context menu or the right click of your menu in Adobe AIR. AIR Uses the ContextMenu class to add menu to your mouse right click.

  import flash.events.ContextMenuEvent;
   import mx.controls.Alert;
   // call this function to create context menu in AIR and FLex
   private function createContextMenu():void
   {
      var myContextMenu:ContextMenu = new ContextMenu();
     this.contextMenu = myContextMenu;       //add menu items

     var myMenuItem1:ContextMenuItem = new ContextMenuItem('Menu Item 1');
     var myMenuItem2:ContextMenuItem = new ContextMenuItem('Menu Item 2');

     myContextMenu.customItems = [myMenuItem1, myMenuItem2 ];

     //add event listeners to menu items
     myMenuItem1.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemClick1);
     myMenuItem2.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, menuItemClick2);

    }     // listener functions for context menu items
       private function menuItemClick1(event:Event):void
       {
        //Write here the code for on click of item 1
        Alert.show('Menu Item 1 clicked');
       }
       private function menuItemClick2(event:Event):void{
           //Write here the code for on click of item 2
           Alert.show('Menu Item 2 clicked');
   }
 ]]>

To restart your application in Adobe AIR

Call this function to restart your application

var app:WindowedApplication = WindowedApplication(Application.application);
var mgr:ProductManager = new ProductManager("airappinstaller");
mgr.launch("-launch " + app.nativeApplication.applicationID + " " + app.nativeApplication.publisherID);
app.close();

Note : PLease add this to your app.XML file inorder for the above code to work.