Sunday, February 14, 2010

Dynamically creating and adding components in your application

Hello Everyone!

This post is mostly for the people who are new to Adobe Flex and have only been working with mxml till now.
Today , we would be talking about how to create and add visual elements , like buttons, panels, html components etc onto you application and how to handle clicks, double clicks in short any kind of mouse events.

Creating Components

Every component in mxml file is actually a class in itself.So all you really need to do is create a new object of this class , and every property ,event , and method of the component you see in mxml can be accessed and used using ActionScript 3.0.

Lets say we want to create a button:
so the code for the same is as following:

var myButton:Button = new Button();//creating a new object
myButton.x=10;//setting the x of the button
myButton.y=15;//setting the y coordinate of the button
myButton.label="I am a button";//the text that appears on the button
myButton.addEventListener(MouseEvent.CLICK,onClick);
//above line is almost like

So you see how easy was it to create and modify the attributes of the button.
Lets go on to the step where we would add it to the application.

Adding the button to the application UI

You can think of the whole as one big class where everything stays.This class has a default place called stage where it adds all the elements to be shown to the user as a part of the UI.
So all you need now is to instruct this class to add the newly created button onto its stage.To do this there is a function called addChild();

So what you would be doing is in the script tag of the mxml you would be using this function and pass the button as a parameter to this function , to finally add the button on the UI.
So the code now will look something like:


[{CData...


public function init():void
{
//code here to initiliaze the button with id myButton.

this.addChild(myButton);//this line is like the final mark saying that yes I want the button to be shown to the user on the specified x and y coordinates

}

{]


Passing the stage to other classes
Using the above code you can add the button to the stage only in the same class as the windowed application.What if you want to add the button to the stage in some other class?
For that you can pass the stage to other classes and in those classes add the button.
Lets say we have a class called MyClass which has the following constructor

public function MyClass(stage:Object):void
{
//code to initialize the button
stage.addChild(myButton);
}

and in the script tag you would do

var myObj:MyClass=new MyClass(this);

The above code is passing the object of WindowedApplication to the object of MyClass and in the constructor , a new button is being created and being added to the WindwedApplication.

With some more experiments you can try some pretty cool stuff by passing the stage and adding or removing elements form the stage from other classes.

Keep Flexing Ppl!

Thursday, February 11, 2010

Editing properties of a component using actionscript

I am sure people have wanted to use /edit properties of a display object using AS 3.
Let me assure you guys that you are minutes away from doing just that, and its really easy and intuitive.

There are two set of properties you would see in any object:
1: Those which are under the section properties in the API documentation
2: Those which are under style under the style section in the API reference

For the ones which are under properties a simple
onjectID.proprtyname=newvalue;
will suffice.

But for the styles, you need to do the following:
objectID.setStyle("propertyname","newvalue");

For example:

Lets say we have a Panel by the ID mypanel , then we can change the properties like
width, height, alpha and all the attributes under properties section using mypanel.width=500, mypanel.height=800, mypanel.alpha=0.4 etc.
But lets say you need to change the backgroundColor, paddingTop, paddingBotton, etc then you need to use commands like mypanel.setStyle("backgroundColor","ff0000") then the backgroundColor of the panel would change to red, you can use the command as shown above for all the possible styles given in the styles section.

The code below shows you an example:
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Button x="195" y="218" label="Button" click="changeWidth()"/>
<mx:Panel x="10" id="panel" y="10" width="250" height="200" layout="absolute">
</mx:Panel>
<mx:Script>
<![CDATA[


public function changeWidth():void
{

this.panel.setStyle("backgroundColor","ff0000");
this.panel.width=500;
}

]]>
</mx:Script>
</mx:WindowedApplication>


I hope this tutorial was useful to ppl.
Awaiting comments.

Monday, February 8, 2010

Fetching data from the microhpone and recording sound.

Hello All,

This tutorial will b short and maybe not fairly complete , but i will be talkin about the major functions and datastructures you would need to fetch data from the microhpne and store it on your system.

The following is ta brief code snippet:

protected function startRecording():void
{
microphone = Microphone.getMicrophone();
microphone.rate = 44;
microphone.gain = 100;
soundClip = new ByteArray();
microphone.addEventListener(SampleDataEvent.SAMPLE_DATA,
microphone_sampleDataHandler);
}

The line microphone = Microphone.getMicrophone(); gets an object by the name microphone which allows you to handle and control the data from the microphone attached on your system.This will return a null if no microphone is detected on your system.The rate , is the rate of data fetch and the gain is the amount of amplification to the sound input.The soundClip object is simply put an array.

The method microphone.addEventListener(SampleDataEvent.SAMPLE_DATA,
microphone_sampleDataHandler);
is the major function for fetching data from the microphone, this says that whenever the sampling is done by the soundcard and the data is being fed to the OS, an event is triggered, and the function microphone_sampleDataHandler() is called.

protected function microphone_sampleDataHandler(event:SampleDataEvent):void
{
while(event.data.bytesAvailable)
{
var sample:Number = event.data.readFloat();
soundClip.writeFloat(sample);
}
}

In the function above , the data being fetched from sample , i.e event.data.readFloat() is being written into the array.
protected function stopRecording():void
{
microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA,
microphone_sampleDataHandler);
saveNote();
subject.text = "";
}

In the function saveNote() you can write the soundClip array into a file, or a database, or any kind of saving you need to do.


Lets hope this tute was helpfule.

Keep Flexing!

Monday, February 1, 2010

Using the Open document API in AIR 2.0

I am back as promised ppl.Within 48 hours of my first tutorial in a series of many to come.
Today we will be talking about how to launch a file with the default appliacation using AIR 2.0 SDK.
Now I am pretty sure that you guys are well aware of how rich and powerful this functionality is.For starters ,you can create a full fledged interoperable file browser.You can let your imagination go wild.;)
So lets get to the code:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
creationComplete="windowedapplication1_creationCompleteHandler(event)"
>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import flash.events.Event;

import mx.events.FlexEvent;

public var file:File=new File();


protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
this.file.browseForOpen("Selec any application you want to run");
this.file.addEventListener(Event.SELECT,runFile);
}

public function runFile(event:Event):void
{
this.file.openWithDefaultApplication();
}


]]>
</fx:Script>
</s:WindowedApplication>


I am pretty sure that the code is self explanatory to you even if you know the meager basics of using Flex.For the people who aren't so used to yet the following is the description:
The function windowedapplication1_creationCompleteHandler(event:FlexEvent) is called whenever the application is started.In this function the application will open a browser window for a user to select a file.

The function runFile(event:Event) is called whenever the user selects the file from the broswer window.We instructed the application to listen for this event using the code his.file.addEventListener(Event.SELECT,runFile);
The moment the file is selected the runFile function is called in which we have called the function file.openWithDefaultApplication();
I am sure I do not need to explain what the function will do.

So try running this code on your new flash builder.

Keep Flexing!

Stay tuned for next tutorial on FilePromise objects in AIR 2.0 which allows the usage of remote files as if its on the local file system.

Friday, January 29, 2010

Mass storage device detection on connection using Flex 4 or AIR 2

Prerequisites: AIR 2.0 ,Flash Builder 4 with Flex 4(build 10485) , a brief knowledge of using flex.

OK guys, I am pretty sure that every flex developer is excited abotu this amazing capability of detection of mass storage when a device is mounted on an OS.The following is the code snippet which allows users to open a file browser with the current directory as the root of the new mounted volume.

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/halo"
creationComplete="windowedapplication1_creationCompleteHandler(event)"
>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import flash.events.StorageVolumeChangeEvent;

import mx.events.FlexEvent;


protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
var s:StorageVolumeInfo=StorageVolumeInfo.storageVolumeInfo;
s.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT,USBMounted);
}
public function USBMounted(event:StorageVolumeChangeEvent):void
{
var file:File=event.rootDirectory;
var files:Array=file.getDirectoryListing();
for each(var f:File in files)
{
trace(f.nativePath);
}
file.browse();
}

]]>
</fx:Script>
</s:WindowedApplication>


In the above code there are two major objects you need to know about, the StorageVolumeInfo and the StorageVolumeChangeEvent that is dispatched whenever there is a change in the StorageVolumeInfo.
The StorageVolumeInfo object is an object which as the name suggest, is an object which stores information about all the storage devices currently connected to the system.

The line:
s.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT,USBMounted);
adds an event listener to the StorageVolumeInfo object , to listen to the event dispatched whenever there is a new volume mounted on the system.

After this in the function USBMounted , using the event object you can access the newly mounted filesystem using the method :
var file:File=event.rootDirectory;

Right now all this program does is opens a browser window with the current directorty as the root of the newly mounted filesystem.But there are many amazing things you can do , like creating a synchonization gadget for specific flash drives, creating your own file browser etc.

Stay tuned for next tutorial on using server sockets.

Monday, January 11, 2010

Video Player with file browsing on your desktop

Hello All, 

Before going on to a tutorial on using sockets in Adobe Flash Builder, I would like to give some introduction on application development using Flex Builder.And after I am done with the this, we will go on to create a UDP based data transfer application.


Before we start with the getting started tutorial , I need you to install Flex Builder 3, the installer of which you can get here. And then, i need you to know , how to create projects and manage project files in the builder ,you can get the tutorial on the same here.


Ok, so assuming that you have conformed to the above two prerequisites, we go on to the next step. The following tutorial will illustrate how to create a Video Player using Flex,simultaneously giving you a brief idea of how objects work in Flex.

Before going on to the coding part, it will be good for you to know how the things work in Flex. The whole application code is divided into two parts, the visual elements as one and the client logic related to that in other part. i.e the visual elements are segregated at one place and the codes related to those and client logic at the other. This framework , helps decouple the view from the actions , so basically a GUI designer and the coder who writes functions can work to build an application parallely. MXML, a declarative XML-based language, is used to describe UI layout and behaviors, and ActionScript™ 3, a powerful object-oriented programming language, is used to create client logic.

So now that we have a few basics cleared, lets go on to designing the view of our application.Here we use only MXML and then debug our application to see how it looks.

Step 1:Create a new flex project, select Desktop Application when given chioce to create a desktop or web application, and name the project as flvplayer.

The moment the creation step is finished you would see the following script on your screen.This is MXML. <?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
</mx:WindowedApplication>
The above defines a window for the application.

Step 2:

The good news is flex has by default some GUI elements already defined, two of them being a video player and buttons, and these are the only two we will need to build our FLV player.
Let us embed a videodisplay in our window with three buttons one for playing the video,one for browsing the flv files and one for pausing. To define a button you need the mxml tag as :
<mx:Button x="10" y="551" label="Play" click=""/>
Here the x and y positions are relative to the container of the button, which right now will be the application window.The label attribute is for the text which willbe shown on the button and the click attribute will define which function to call when the button is clicked on. As you can see, here you are decoupling the code you need when you press the button. To define the videodisplay you need the tag:
<mx:VideoDisplay x="10" y="10" width="778" height="533" id="myVidDisp"/>
Here the attributes x,y ,width and height are self-explanatory. The id attribute gives a name to this element in the application.This is obvious , as suppose we need two media players in the application window then we need to identify them by two different names. So now we will embed all the above requred tags in the MXML. Your code now shoule look like :
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" borderColor="#5E5959"
backgroundGradientAlphas="[1.0, 1.0]"
backgroundGradientColors="[#29F27E, #0C776E]" >
<mx:VideoDisplay x="10" y="10" width="778" height="533" id="myVidDisp"/>
<mx:Button x="10" y="551" label="Play" click=""/>
<mx:Button x="63" y="551" label="Pause" click=""/>
<mx:Button x="691" y="551" label="Browse Files" click=""/>
</mx:WindowedApplication>

Step 3:Giving life to the dumb GUI.

Now that we have setup a GUI for ourselves, lets go on to give it a life. To embed code in the xmml, we need the script tag. <mx:Script>
<![CDATA[

]]>
</mx:Script>
In between the CDATA tag would lie our code .The life of the application. Let us build three functions : 1.To browse a a .flv file
2.To pause a running video
3.To play a puased video
Now , the prototype of a function in AS 3 is as follows:
<scope> function <functionname>(<passedarguments>):<returntype>
{

}
so if we want a function onPlayClick() which is called when the user clicks on the play button it should look like :
public function onPlayClick():void
{
}
similarly we will define two more functions onPauseClick() and onBrowseClick() and put them in the script tag. also in the click attributes of the play , pause and browse files button you need to put onPlayClick() ,onPauseClick and onBrowseClick() respectively, after which your code should look like:
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" borderColor="#5E5959"
backgroundGradientAlphas="[1.0, 1.0]"
backgroundGradientColors="[#29F27E, #0C776E]" creationComplete="init()" >
<mx:VideoDisplay x="10" y="10" width="778" height="533" id="myVidDisp"/>

<mx:Button x="10" y="551" label="Play" click=""/>
<mx:Button x="63" y="551" label="Pause" click=""/>
<mx:Button x="691" y="551" label="Browse Files" click="browseAndPlay()"/>
<mx:Script>
<![CDATA[
public function onPlayClick():void
{

}

public function onPauseClick():void
{

}

public function onBrowseClick():void
{


}
]]>

</mx:Script>

</mx:WindowedApplication>

Step 4:Throwing life into the functions

Now for the play and pause functions the code is as simple as myVidDisp.play() and myVidDisp.pause(). The coding for the browse function is a bit tricky but nothing a newbee cannot grasp. The code is as follows:
var file:File=new File();
var Filter:FileFilter = new FileFilter("Flash Video","*.flv");
file.browseForOpen("Select a Video File",[Filter]);
file.addEventListener(Event.SELECT,fileSelected);
The function
file.browseForOpen("Select a Video File",[Filter]);
opens a native broswer for the user to select files to open for the video player.
And the function
file.addEventListener(Event.SELECT,fileSelected);
can be compared to the click attribute for the buttons we defined above.
Basically this function says that, for the file, when the event Event.SELECT occurs, that is user selects a file in the browser, you need to call the function fileSelected().

Now we need to define the function fileSelected.
public function fileSelected(event:Event):void
{
var file:File=event.target as File;
this.myVidDisp.source=file.nativePath;
}
Here you can see that we passed the event as an argument as the event stores information about the file seleted by the user.

The statement var file:File=event.target as File, defines a file and typecasts event.target which is an Object to a type of File Object.
The statement this.myVidDisp.source=file.nativePath tells the compiler to change the source of the videoplayer to the nativepath of the selected file.
You final code should look like:
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" borderColor="#5E5959"
backgroundGradientAlphas="[1.0, 1.0]"
backgroundGradientColors="[#29F27E, #0C776E]" >
<mx:VideoDisplay x="10" y="10" width="778" height="533" id="myVidDisp"/>
<mx:Button x="10" y="551" label="Play" click="onPlayClick()"/>
<mx:Button x="63" y="551" label="Pause" click="onPauseClick()"/>
<mx:Button x="691" y="551" label="Browse Files" click="onBrowseClick()"/>
<mx:Script>
<![CDATA[
public function onPlayClick():void
{

}
public function onPauseClick():void
{

}
public function onBrowseClick():void
{
var file:File=new File();
var Filter:FileFilter = new FileFilter("Flash Video","*.flv");
file.browseForOpen("Select a Video File",[Filter]);
file.addEventListener(Event.SELECT,fileSelected);

}

public function fileSelected(event:Event):void
{
var file:File=event.target as File;
this.myVidDisp.source=file.nativePath;
}
]]>
</mx:Script>

<mx:Script>
<![CDATA[

]]>
</mx:Script>
</mx:WindowedApplication>

Step 5: Debug the application and enjoy your own hand tailored video player.

Click on the browse button, a browser window will open , select a .flv file and see your player in action. Stay tuned for some more tutorials before the weekend.

Wednesday, December 9, 2009

Impressive launch of the new AIR 2.0

I have been a RIA (Rich Internet Application ) developer from the last two years, developing applications from small ones i.e for just the sake of it to big ones i.e planning to use a part of it commercially.Some of my data visualization applications are being used in a specific financial firm , localted globally (though i can not divulge the name of the firm as yet).And all this I have done using Adobe Flex (for thoseweb developers who do not know about flex,had I been you, I would've stopped reading this right now and started searching for what Flex is all about), and as far as the not so naive developers are concerned (ppl who know about flex or have had a development experience ) I would like to share my notion of it as the next Java.It is completely going to be the 'thing'.

My expectations were pseudo confirmed when i came to know about AIR 2.0 , AIR is the short for Adobe Integrated Runtime (something analogous to JVM when compared to java), which had extended the capabilities of Flex drastically , by including native command line interactions, microphone data access, socket listening capabilities and hoard of other things which I read about in an article for Adobe MAX.

The moment i came to know about it, I downloaded the nightly build for AIR 2.0 from the Adobe's website, and started using it on my new Flash Builder Beta 2.

Id be soon posting about my first UDP data transfer application using AIR 2.0
So guys, keep checking.