Category Archives: Adobe_AIR/FLEX

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

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.
}

How to drag and drop a file from outside to your flex or AIR application and render it correctly?

Actually we have to do this by registering your application with the eventlisteners for NATIVE_DRAG_ENTER and NATIVE_DRAG_DROP.
The following code shows how to do this.
Just copy and paste the code to your MXML file and see the result.
Drag and drop an image file from outside to your AIR application.


        import mx.controls.Alert;
        import mx.controls.Image;
        import flash.filesystem.File;

        private function init():void{
               this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER,onDragIn);
               this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP,onDrop);
        }

        private function onDragIn(event:NativeDragEvent):void{
          NativeDragManager.acceptDragDrop(this);
        }

        private function onDrop(event:NativeDragEvent):void{
          var dropfiles:Array = event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
          for each (var file:File in dropfiles){
            switch (file.extension.toLowerCase()){
              case "png" :
                addImage(file.nativePath);
                    break;
              case "jpg" :
                addImage(file.nativePath);
                break;
              case "jpeg" :
                addImage(file.nativePath);
                break;
              case "gif" :
                addImage(file.nativePath);
                break;
              default:
                Alert.show("Unmapped Extension");
              }
            }
          }

          private function addImage(nativePath:String):void{
            var i:Image = new Image();
            if(Capabilities.os.search("Mac") >= 0){
              i.source = "file://" + nativePath;
            } else {
              i.source = nativePath;
            }
            this.addChild(i);
          }
        ]]>

Adding Links in Menu in Adobe AIR/ FLEX.

Hi all…

In this tutorial I will show you how to add links in a menu in Adobe AIR/ FLEX.
It is really simple. Just add a normal menu item and on the click handler for menu items match the label and navigate to the URL, that’s all.
Check out this example.
Change the mx:Application to mx:windowedApplication to work this example as AIR application.



	
		
					
						
						
					
					
						
					
				;

			// create menu items
			private function init():void {
				menuCollection = new XMLListCollection(menubarXML);
			}

			// click handler for menubar
			private function menuHandler(event:MenuEvent):void
			 {
				if(event.item.@label=="Google.com")
				{
					var url:URLRequest = new URLRequest('http://www.google.com');
					navigateToURL(url,'_parent');
				}
				else if(event.item.@label=="Yahoo.com")
				{
					url = new URLRequest('http://www.yahoo.com');
					navigateToURL(url,'_parent');
				}
			}
		]]>
	
	
	
	

Link in menu example in Adobe AIR

Listening to keyBoard in Adobe AIR/FLEX….

Hi all….

We all need to know which key is pressed in an application up on which we may need to take an action. For example if the user presses “Ctrl + s” we know he want to save. So for that we need to listen to keyBoard events. For this we use the keyBoard event Listener. First we register our application with the KeyBoard eventListener. After that we will implement the callback function associated with the event. Here the callback function is named “keyListener”. See how it works.
Copy and paste to your MXML file and view the console for the output after pressing any key in the keyboard.




    
        

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

How to open a new window in Adobe AIR?

Hi all ….

In this example I will show you how to open a new window from an adobe AIR Application.

First you create a new Flex Project and named FirstWindow.
Now you have FirstWindow.mxml in your project. Go on open it and copy the following code to it.



	
		
	


Now right click on the src folder and create an MXML component. select Window from the Dropdown and name it SecondWindow.
Now you have SecondWindow.mxml.

Take a look at the screenshot

Flex open window example

Flex open window example

Flex open window example

Flex open window example

Now copy this code to it.



	
		
	

It’s all done. Now run it.

Flex open window example

Flex open window example

ToolTip Sound in Adobe AIR/FLEX…

Sometimes we may need to have a sound when we hover over something, i.e when a tooltip appears.
Actually this can be done easily by adding an eventListener to the corresponding control.
Take a look at the example.
This line is the important line.

      myLabel.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, myListener);

The function myListener gets called when we hover over the label thus producing the sound.
What you have to do is to just copy and paste the following code to your file.

       import mx.events.ToolTipEvent;
     import flash.media.Sound;

     [Embed(source="msgAlert.mp3")]

     private var myToolTipSound:Class;
     private var mySound:Sound;

     private function init():void {
        myLabel.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, myListener);
        mySound = new myToolTipSound();
     }
      public function playSound():void {
        mySound.play();
     }
     private function myListener(event:ToolTipEvent):void {
        playSound();
     }
  ]]>
   

Alert Button with Image in Adobe AIR/FLEX…

We usually see only alerts with text only, but in Adobe AIR and FLEX we can have alerts with our images in it. That’s really cool right.
Take a look at this simple example. It places an image in the alert.
Make sure that you have the image named “alert_image.png” in your “src” folder or otherwise give the specific path.



 
        
        


No Image

File Operations in Adobe AIR/FLEX

The following example shows how to deal with a simple text file in Adobe AIR/FLEX.
This example illustratesd how to write a string to a text file and save it in the desktop.
However you can use the “application directory” but make sure that you have necessary write permission to access the directory.




	

Please leave your valuable comments…..

Play an MP3 in Adobe AIR/FLEX

Often in out applications we need to play sounds , so this code explains how to play, stop and resume an mp3 sound in Adobe AIR/FLEX.
What you have to do is to copy the following code and place it inside your “mx:Script” tag.
After that place three buttons for play, pause and stop and connect it to the three functions coded below.
Make sure that you have the sound file in your applications directory.


import adobe.utils.CustomActions;
import air.net.URLMonitor;
import flash.media.Sound;
import flash.media.ID3Info;
import flash.net.URLRequest;

var sound:Sound = new Sound(new URLRequest("app:/my_sound.mp3"));
var my_channel:SoundChannel;
var pausePos:int = 0;
[Bindable]
private function play():void
{
       my_channel= sound.play();
}
private function stop():void
{
      pausePosition = my_channel.position;
      my_channel.stop();
}
private function resume():void
{
       my_channel = sound.play(pausePos);
}

Please leave your valuable comments.

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…….

Dynamically Load CSS in Adobe AIR/FLEX / Load css in Adobe AIR/FLEX using Class.

This example shows how to dynamically load css in Adobe AIR / FLEX.
Here in this example Panel id the tag name for the panel control. Drag a panel control to your design then copy the code to your source file. “myTabs” is the class for the CSS.




	Panel {
   borderColor:  #CBE0FF;
   border-style:solid;
   borderThickness: 1;
   borderThicknessLeft: 0;
   borderThicknessTop: 0;
   borderThicknessBottom: 0;
   borderThicknessRight: 0;
   cornerRadius: 4;
   highlightAlphas: 1, 0.49;
   headerColors: #0066ff, #ffffff;
   backgroundColor: #F5FAFF;
}
TitleWindow{
	borderColor:#CBE0FF;
   border-style:solid;
   borderThickness: 1;
   borderThicknessLeft: 0;
   borderThicknessTop: 0;
   borderThicknessBottom: 0;
   borderThicknessRight: 0;
   cornerRadius: 4;
   backgroundAlpha: 1;
   highlightAlphas: 1, 0.49;
   headerColors: #0066ff, #ffffff;
   backgroundColor: #F5FAFF;
   footerColors: #0099ff, #ffffff;
}

ComboBox
{
	cornerRadius: 4;
  	highlightAlphas: 0.52, 0.52;
	fillAlphas: 0, 1, 1, 1;
	fillColors: #0066ff, #ffffff, #ff9900, #eeeeee;
	borderColor: #cccccc;
	font-family:arial;
	font-size:11px;
	font-weight:normal;
	color:#000000;
}

ApplicationControlBar {
   highlightAlphas: 1, 0.42;
   fillAlphas: 0.78, 0.8;
   fillColors: #619ffc, #ffffff;
   backgroundAlpha: 1;
   cornerRadius: 1;
   shadowDistance: 1;
}
TabBar {
	tab-style-name: "myTabs";
	selected-tab-text-style-name: "mySelectedTabs";
    padding-left:0px;
	padding-right:0px;
	padding-top:0px;
	padding-bottom:0px;
	vertical-gap:0px;
	horizontal-gap:0px;
}
.myTabs {
   cornerRadius: 4;
   highlightAlphas: 0.30, 0;
   fillAlphas: 0.60, 0.40;
   /* fillColors: #c0dcf9, #e8f0f8; */
   fillColors: #95d0fe, #95d0fe;
   borderColor: #ffffff;
   border-thickness:4px;
   color: #0b333c;
   fontFamily: Arial;
   font-weight:bold;
   font-size:11px;
   backgroundColor: #f8d49d;
   padding-left:1;
   text-align:left;
   horizontal-gap:4px;
   vertical-align:middle;

}

.mySelectedTabs {
   textAlign: left;
   fontFamily: Arial;
   fontWeight: normal;
}
HBox{
 backgroundColor: #ffffff;
}


	
	
		
	
	
	
	
	
		
			
			
			
		
	
	
		
	
	
	
	
		
		
		
		
	
	
	
	
	
		
	
	
	
	


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);

Trim() function in ActionScript(Adobe AIR , FLEX etc)…

The function for trim in ActionScript is defined inside StringUtil Class.
Checkout the following function.

public function stringTrim(result:String):String{

      result = StringUtil.trim(result);
trace(result);
return result;

}

Please post your valuable comments if the post was useful.

The function for trim in ActionScript is defined inside StringUtil Class.
Checkout the following function.

public function stringTrim(result:String):String{

      result = StringUtil.trim(result);
trace(result);
return result;

}

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);