Count Up Timer

A simple flex application for the implementation of the Timer, which can have buttons for Start, Pause and Reset.

Program:-

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
fontWeight="bold">
<mx:Script>
<![CDATA[

[Bindable] private var second:Number=0;
[Bindable] private var minute:Number=0;
[Bindable] private var hour:Number=0;

private var timer:Timer = new Timer(10);
public var cnt:int = 1;

private function init():void {
timer.addEventListener(TimerEvent.TIMER, my_timer_timer);
timer.start();
lbl1.text = "1";
}

private function my_timer_timer(evt:TimerEvent):void
{
second = int(lbl1.text);
txt_display.text = hour+':'+ minute+':'+second;
second++;
lbl1.text = String(second);
if(second>59)
{
minute++;
second = 0;
lbl1.text = String(second);
if(minute>59)
{
hour++;
minute=0;
second =0;
lbl1.text = String(second);
}

}

}

private function pause():void
{

timer.stop();
txt_display.text = hour+':'+ minute+':'+second;

}
private function reset():void
{
minute=0;
hour=0;
second=0;
txt_display.text = hour+':'+ minute+':'+second;
}
]]>
</mx:Script>
<mx:Panel width="275" height="305" layout="absolute" borderColor="#000000" title="TIMER" horizontalCenter="19" verticalCenter="8.5">
<mx:Label id="lbl1" enabled="false"/>
<mx:Button x="20.5" y="176" label="Start" id="btn_start" click="{init()}" fillColors="[#8080ff, #b3f4f4]"/>
<mx:TextInput x="32.5" y="102" height="35" width="190" id="txt_display" fontSize="22" textAlign="center"/>
<mx:Button x="97" y="176" label="Pause" id="btn_pause" click="{pause()}" fillColors="[#8080ff, #b3f4f4]"/>
<mx:Button x="186" y="176" label="Reset" id="btn_reset" click="{reset()}" fillColors="[#8080ff, #b3f4f4]"/>
</mx:Panel>

</mx:Application>


Screen Shot:-

Flex gradient background

A simple thing that I learnt today in Flex (I am very much a beginner as you can see) – adding a gradient to the flex background.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" backgroundGradientColors="[0xAAAAAA,0x000000]" horizontalAlign="left" verticalGap="15" horizontalGap="15">

This will add a horizontal gradient starting from light gray and ending in black – looks real nice.

Remember to prefix your color codes with 0x (zero and alphabet x) – and not #

Remote access using Flex

This program sends a URL request to the server and then the response is received  and the content is displayed in a formatted way……

<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ import mx.controls.Label; import mx.controls.Text; import flash.net.navigateToURL; import flash.net.sendToURL; public var myurl:String="http://www.schogini.co.in/mca/mca2.php?name="; var loader = new URLLoader(); //This function will send URL request and load the content to //an object of URLloader. EventListenere is added to this object. //The function loadcomplete is invoked when the event is completed. function TextSearch():void { var inputtext:String = text1.text; var newurl:String = myurl + inputtext; var url:URLRequest= new URLRequest(newurl); loader.addEventListener(Event.COMPLETE,loadComplete); loader.load(url); } //This function copy the content in the object of URLLoader to a //string. Afert removing '|' symbol the string is displayed on the screen. function loadComplete(e) { var result:String = loader.data; var newarray:Array = new Array(); newarray = result.split("|",result.length); lab1.text = "Name:"+newarray[0]; lab2.text = "Address:"+newarray[1]; lab3.text = "Ph.No.(Home):"+newarray[2]; lab4.text = "Ph.No.(Mobile):"+newarray[3]; lab5.text = "Blood Group:"+newarray[4]; lab6.text = "Email ID:"+newarray[5]; } ]]> </mx:Script> <mx:TextInput x="80" y="65" id="text1" height="24" fontSize="12"/> <mx:Button x="264" y="65" id="Button" label="search"  click="TextSearch();" fontWeight="bold" fontSize="12"/> <mx:Label x="80" y="197" id="lab1" fontWeight="bold" fontSize="10"/> <mx:Label x="80" y="227" id="lab2" fontWeight="bold" fontSize="10"/> <mx:Label x="80" y="255" id="lab3" fontWeight="bold" fontSize="10"/> <mx:Label x="80" y="285" id="lab4" fontWeight="bold" fontSize="10"/> <mx:Label x="80" y="313" id="lab5" fontWeight="bold" fontSize="10"/> <mx:Label x="80" y="345" id="lab6" fontWeight="bold" fontSize="10"/> </mx:Application>

The output is ……….

Count Up Timer

A simple Flex application for Count Up Timer in which one can Start , Pause and Reset it.

Program:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
fontWeight="bold">
<mx:Script>
<![CDATA[

[Bindable] private var second:Number=0;
[Bindable] private var minute:Number=0;
[Bindable] private var hour:Number=0;

private var timer:Timer = new Timer(10);
public var cnt:int = 1;

private function init():void {
timer.addEventListener(TimerEvent.TIMER, my_timer_timer);
timer.start();
lbl1.text = "1";
}

private function my_timer_timer(evt:TimerEvent):void
{
second = int(lbl1.text);
txt_display.text = hour+':'+ minute+':'+second;
second++;
lbl1.text = String(second);
if(second>59)
{
minute++;
second = 0;
lbl1.text = String(second);
if(minute>59)
{
hour++;
minute=0;
second =0;
lbl1.text = String(second);
}

}

}



private function pause():void
{

timer.stop();
txt_display.text = hour+':'+ minute+':'+second;

}
private function reset():void
{
minute=0;
hour=0;
second=0;
txt_display.text = hour+':'+ minute+':'+second;
}
]]>
</mx:Script>
<mx:Panel width="275" height="305" layout="absolute" borderColor="#000000" title="TIMER" horizontalCenter="19" verticalCenter="8.5">
<mx:Label id="lbl1" enabled="false"/>
<mx:Button x="20.5" y="176" label="Start" id="btn_start" click="{init()}" fillColors="[#8080ff, #b3f4f4]"/>
<mx:TextInput x="32.5" y="102" height="35" width="190" id="txt_display" fontSize="22" textAlign="center"/>
<mx:Button x="97" y="176" label="Pause" id="btn_pause" click="{pause()}" fillColors="[#8080ff, #b3f4f4]"/>
<mx:Button x="186" y="176" label="Reset" id="btn_reset" click="{reset()}" fillColors="[#8080ff, #b3f4f4]"/>
</mx:Panel>

</mx:Application>

Screen Shot:

Bank Interest Calculation Using Flex

It is an application to calculate simple and compound interest.

Accept user input for principle amount(P),year(N),interest rate(R).

Here it can calculate both simple and compound interest.

Simple interest is calculated using the mathematical formulae I = PNR/100 and

compound inetrest can be calculated using I = (P(1+r/100)^N)-P

Code for the calculation is as follows:

<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function calculate(eventObj:MouseEvent):void
{
var p:int=int(txtp.text);
var n:int=int(txty.text);
var r:int=int(txtr.text);
if((txtp.text=="")||(txty.text=="")||(txtr.text=="")||((!rdbs.selected)&&(!rdbc.selected)))
{
Alert.show("Please fill all fields before submitting...");
}
if(rdbs.selected)
{
var i:int=(p*n*r)/100;
}
if(rdbc.selected)
{
var i:int=(p*(Math.pow((1+r/100),n)))- p;
}
txti.text=String(i);
}
]]>
</mx:Script>

Output must be shown like follows:

Retreive data from a PHP file using Adobe Flex

Here you are going to connect a Flex application with PHP.
The values are saved as an XML format in that PHP file.

You can create a new Flex Project and paste the following code in the mxml file:

<?xml version="1.0" encoding="utf-8"?> <!--mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="productsRequest.send()" --> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:XML id="productsRequest" source="http://localhost/flex/products.php"></mx:XML> <mx:DataGrid x="20" y="80" id="productGrid" width="400"  dataProvider="{productsRequest..product}" > <mx:columns> <mx:DataGridColumn headerText="Name" dataField="name" /> <mx:DataGridColumn headerText="Price" dataField="price" /> </mx:columns> </mx:DataGrid> </mx:Application>

Here you are going to use <mx:XML> which connects the mxml application with a php file.
Then an <mx:DataGrid> is used which shows a datagrid with specified columns.

Then create a folder inside /xamp/htdocs/
Here I have created a folder named flex and inside that folder create a new php file which I named as products.php
Copy the code below into products.php

<?php $a = '<?xml version="1.0" encoding="utf-8" ?><products> <product><name>Mobile Phone</name><price>$199</price></product> <product><name>Car Charger</name><price>$34</price></product> <product><name>iPhone</name><price>$149</price></product> <product><name>10 TB HDD</name><price>$150</price></product> <product><name>Acer Laptop</name><price>$600</price></product> <product><name>HP Laptop</name><price>$640</price></product> <product><name>iPod</name><price>$140</price></product> </products>'; header("Content-Type: text/xml"); print $a; ?>

Here in the  php file, data is saved in XML format and it is printed inside the datagrid defined in the mxml file.

Start Xamp and run the mxml file in Adobe Flex.
You can see a data grid with populated values.

Flex – PHP – MySQL

Example — Employee listing from ’employee’ table

First Create a PHP file, which connects to the data base, query the table, retrieve the value and store it in a XML file.

list.php

<?php
header('Content-Type: text/xml');
?>
<employeedetails>
<?php
require_once("DB.php");

$dsn = 'mysql://root@localhost/test';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

$res = $db->query( "SELECT firstname, lastname, designation, department FROM employees" );
while( $res->fetchInto( $row ) )
{
?>
<employee>
<first><?php echo( $row[0] ); ?></first>
<last><?php echo( $row[1] ); ?></last>
<designation><?php echo( $row[2] ); ?></designation>
<department><?php echo( $row[3] ); ?></department>
</employee>
<?php
}
?>
</employeedetails>

Now we need to wrap a Flex user interface around the XML list.php page. Create a data viewer for XML data that comes from PHP with Flex.
list.mxml file, used for this is copied below.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:XML id="mydata" source="http://localhost/flex_php/list.php"></mx:XML>

<mx:DataGrid id="employeelist" x="10" y="10" dataProvider="{mydata..employee}">
<mx:columns>
<mx:DataGridColumn dataField="first" />
<mx:DataGridColumn dataField="last" />
<mx:DataGridColumn dataField="designation" />
<mx:DataGridColumn dataField="department" />
</mx:columns>
</mx:DataGrid>
</mx:Application>

The <mx:XML> tag defines the location of XML data source. Its our list.php file.
<mx:DataGrid> tag is a Flex control that displays data in a tabular format.
To tell the DataGrid control which fields to display, create an <mx:columns> tag that contains <mx:DataGridColumn> tags for each field.

Example — Insert data into ’employee’ table

First Create a PHP file, which connects to the data base, prepares the INSERT statement, and runs it with the variables provided by the POST arguments that will come from the Flex application. Flex applications use POST data just like any other web client, which makes it easy to connect with existing web applications.

addEmployee.php

<?php
header('Content-Type: text/xml');

require_once("DB.php");

$dsn = 'mysql://root@localhost/test';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

$sth = $db->prepare(
"INSERT INTO employees ( firstname, lastname, designation, department ) VALUES ( ?, ?, ?, ? )"
);

$db->execute( $sth,
array( $_POST['firstname'], $_POST['lastname'], $_POST['designation'], $_POST['department'] )
);
?>

The next step is to build the frontend form that will add employee to table. This form uses the addEmployee.php script on the server to add new entries to the database. The MXML script for the form is shown below.

addEmployee.mxml
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:HTTPService id="srv" url="http://localhost/flex_php/addEmployee.php" method="POST">
<mx:request>
<firstname>{firstname.text}</firstname>
<lastname>{lastname.text}</lastname>
<designation>{designation.text}</designation>
<department>{department.text}</department>
</mx:request>
</mx:HTTPService>


<mx:Form>
<mx:FormItem label="First Name">
<mx:TextInput id="firstname"/>
</mx:FormItem>
<mx:FormItem label="Last Name">
<mx:TextInput id="lastname"/>
</mx:FormItem>
<mx:FormItem label="Designation">
<mx:TextInput id="designation"/>
</mx:FormItem>
<mx:FormItem label="Department">
<mx:TextInput id="department"/>
</mx:FormItem>
<mx:FormItem>
<mx:Button label="Add Employee" click="srv.send()"/>
</mx:FormItem>
</mx:Form>
</mx:Application>

At the top of the file is the definition of the HTTP service that the PHP addEmployee.php script provides.

At the bottom is the form, with all the labels, text input areas and “Add Employee” button.

Connecting Flex with php

1. Go to File > New > Flex Project.
2. In the dialog box, type helloWorld as the project name, and specify a project directory called helloWorld under the web root. Select Web application option as the application type, and then select an application server type of PHP.
3. Also give main source folder name
4. In the design view change value for layout as ‘vertical’.
5. Write following code in helloworld.mxml of code view.
<mx:HTTPService id="phpService"
url="http://localhost/helloWorld/helloWorld.php"
resultFormat="object" result="showResult()"/>
We can use an HTTPService component with any kind of server-side technology, including PHP pages.Here ,the service has an ID of phpService and a URL pointed to the helloWorld.php file, and the result format is generic object. The service is also set to call the showResult() function when it gets a result.
To actually use the service, its send method needs to be called.
For that we use <mx:Button> control .
<mx:Button label=”Call PHP” click=”phpService.send()”/>
Now, we need to create the showResult() function in an <mx:Script> block, below the <mx:HTTPService> tag.
<mx:Script>
<![CDATA[
import mx.controls.Alert;
privatefunction showResult():void {
Alert.show(phpService.lastResult as String,'Message from PHP');
}
]]>
</mx:Script>
The ActionScript code first declares an Import statement,which allows the application to use the Alert class from the mx.controls package. Secondly, it creates the showResult() function. This function displays an alert pop-up with the title "Message from PHP." The text within the alert box is the result from the HTTPService call to the helloWorld.php file.
6. Create a directory inside xampp/htdocs/ as helloWorld and a file helloworld.php inside that directory. The code is given below:
<?php
print "Hello world";
?>
7. Run the application to get the result as shown below.