Posted by: Tushar | November 26, 2010

Making AMF calls from AJAX (JSP, Java)

AMF (Action Message Format) Calls can be triggered from Java Client as well. AMFConnection class can be used for the same. Documentation is available at: http://livedocs.adobe.com/blazeds/1/javadoc/flex/messaging/io/amf/client/AMFConnection.html

Below is a simple example usage:

  • Setup BlazeDS and create simple destination as explained by Sujit Reddy on his blog. URL: http://sujitreddyg.wordpress.com/2008/01/14/invoking-java-methods-from-adobe-flex/
  • Create following two JSP files – ‘index.jsp’, ‘callAMF.jsp’. Copy these files on server. In my case, application name was ‘JavaAMFClientExample’. I copied files to root of ‘JavaAMFClientExample’ application on server.
  • Create Java Class ‘JavaAMFClientImpl’; add BlazeDS JAR files to Java project. Copy class file in appropriate directory on server. In my case path of class file was – <TomcatServer\webapps>\JavaAMFClientExample\WEB-INF\classes\com\tushar\JavaAMFClientExample\JavaAMFClientImpl.class
  • Run index.jsp and click ‘Call Service’ button. This will make an AJAX call to ‘callAMF.jsp’ and will display server response in same page.

index.jsp:

<HTML>
<head>
<style type="text/css">
table {
 border-width: 0px;
 border-spacing: 2px;
 border-style: dashed;
 border-color: gray;
 border-collapse: separate;
 background-color: white;
}
table td {
 border-width: 0px;
 padding: 0px;
 border-style: inset;
 border-color: gray;
 background-color: white;
 -moz-border-radius: 0px 0px 0px 0px;
}
p, li, td { font-family: verdana;  font-size: 12px }

</style>
<script type="text/javascript">
{
 var xmlHttp;
 try    {  // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
 catch (e) {  // Internet Explorer
 try {
 xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 }
 catch (e) {
 try {
 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 catch (e) {
 alert("Your browser does not support AJAX!");
 }
 }
 }

 xmlHttp.onreadystatechange=function()
 {
 if(xmlHttp.readyState==4) {
 document.getElementById("response").innerHTML = xmlHttp.responseText;
 }
 }

 function onFormSubmit()
 {
 var destination = document.getElementById("destination");
 var method = document.getElementById("method");
 var name = document.getElementById("name");

 if(destination != null){
 destination = destination.value
 }
 if(method != null){
 method = method.value
 }
 if(name != null){
 name = name.value
 }
 var params = "destination="+destination+"&method="+method+"&name="+name+"&sid="+Math.random();
 var url="callAMF.jsp?"+params;
 xmlHttp.open("GET",url,true);
 xmlHttp.send(null);
 }
}
</script>
</head>
<BODY>
<table border="0" width="100%" cellspacing="0" cellpadding="0">
 <tr>
 <td>
 <table border="1" width="100">
 <tr>
 <td colspan="2" align="center"><div><h5>Test AMF Call</h1></div></td>
 </tr>
 <tr>
 <td>Destination:</td>
 <td><INPUT TYPE=TEXT id="destination" value="CreatingRpc" SIZE=20></td>
 </tr>
 <tr>
 <td>Method:</td>
 <td><INPUT TYPE=TEXT id="method" value="getResults" SIZE=20></td>
 </tr>
 <tr>
 <td>Name:</td>
 <td><INPUT TYPE=TEXT id="name" value="Tushar" SIZE=20></td>
 </tr>
 <tr>
 <td></td>
 <td><input type="submit" value="Call Service" onclick="onFormSubmit()" /></td>
 </tr>
 </table>
 </td>
 </tr>
 <tr>
 <td align="left"><div id="response"></td>
 </tr>
</BODY>
</HTML>

callAMF.jsp:

<%@ page language="java" %>
<%@ page import="com.tushar.JavaAMFClientExample.*" %>

<%
String destination=request.getParameter("destination");
String method=request.getParameter("method");
String name=request.getParameter("name");

JavaAMFClientImpl javaAMFClientService = new JavaAMFClientImpl();
Object obj = javaAMFClientService.sendAMFMessage(destination, method, name);
%>
<p>Message from Server: <%=obj%><p>

JavaAMFClientImpl.java

package com.tushar.JavaAMFClientExample;

import flex.messaging.io.amf.client.AMFConnection;
import flex.messaging.io.amf.client.exceptions.ClientStatusException;
import flex.messaging.io.amf.client.exceptions.ServerStatusException;

public class JavaAMFClientImpl {

 public Object sendAMFMessage(String destination, String method, String name) throws ClientStatusException, ServerStatusException {
 // Create the AMF connection.
 AMFConnection amfConnection = new AMFConnection();
 // Connect to the remote url.
 String url = "http://localhost:8080/JavaAMFClientExample/messagebroker/amf";
 try
 {
 amfConnection.connect(url);
 }
 catch (ClientStatusException cse)
 {
 System.out.println(cse);
 return null;
 }

 // Make a remoting call and retrieve the result.
 try
 {
 Object result = amfConnection.call(destination+"."+method, name);
 return result;
 }
 catch (ClientStatusException cse)
 {
 System.out.println(cse);
 return null;
 }
 catch (ServerStatusException sse)
 {
 System.out.println(sse);
 return null;
 }
 finally {
 amfConnection.close();
 }
 }
}

Java Project:

Flex Client:

JSP Client:

JavaScript AMF Implementation:

James Ward has created a Pure JavaScript AMF implementation. Here are more details: http://css.dzone.com/news/amfjs-%E2%80%93-pure-javascript-amf

Posted by: Tushar | July 25, 2010

iPhone Simulator – Add Images in ‘Photos’

Here is a quick tip to add images in iPhone Simulator for Mac (Xcode).

  • Open iPhone Simulator
  • Navigate to image using ‘Finder’
  • Drag image from ‘Finder’ to iPhone Simulator
  • This will open the image in ‘Safari’ on iPhone Simulator
  • Now Click and Hold on the image in ‘Safari’
  • This will open a menu with option – ‘Save Image’, ‘Copy’ and ‘Cancel’
  • Hit ‘Save Image’. This will save the image for iPhone Simuator

Once images are saved, those are listed in Photos > Saved Photos

For me this was quite tricky so thought of sharing. Hope this helps someone :)

Posted by: Tushar | November 20, 2008

Flex 3 Auto-Resize TextInput Control? How?

Here is a quick solution to add Auto-Size functionality to TextInput control in Flex 3.

AutoSizeTextInput.class

package com.tushar.controls {
	
	import flash.events.Event;	
	import mx.controls.TextInput;
	
	public class AutoSizeTextInput extends TextInput {
		
		private var txtSpan:uint = 10;
		
		public function AutoSizeTextInput() {
			super();
			this.addEventListener(Event.CHANGE, onTextChange);
		}
		
		private function onTextChange(evnt:Event):void {
			this.textField.scrollH = 0;
			this.width = this.autoSizeWidth;
		}
		
		override protected function commitProperties():void {
			super.commitProperties();
			this.textField.scrollH = 0;
			this.width = this.autoSizeWidth;
		}
		
		private function get autoSizeWidth():uint {
			return (this.textWidth+txtSpan);			
		}
	}
}

Usage in MXML:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
	xmlns:custom="com.tushar.controls.*"
	layout="vertical">
	<custom:AutoSizeTextInput text="Hello world! "/>
</mx:Application>

Not sure if this method is perfect! Do let me know if there is any better way to implement this :)

Posted by: Tushar | November 4, 2008

AS3 FlexNativeMenu and dataprovider

Yesterday I faced an issue with FlexNativeMenu (popup menu) and its dataprovider. Looks like, FlexNativeMenu does not recognize the changes made to dataprovider.

Situation: I was wanted to disable the menu item based on the Label (clicking which I am showing the FlexNativeMenu as a Popup menu).

So, before showing the menu (FlexNativeMenu.display) I tried to update the Dataprovider (XML). But changes were not reflected in the menu! Further, Error #1009 was reported after clicking any menuItem.

I even tried to assign the dataprovider again hoping that this way problem will get resolved.
But this time also, changes were not reflected. However, Menu was updated after clicking twice on the same label. But clicking on any menuItem was still reporting Error #1009.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
layout="horizontal" creationComplete="init();">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.FlexNativeMenuEvent;
import mx.containers.HBox;
import mx.controls.TextInput;
import mx.controls.Label;
import mx.controls.FlexNativeMenu;

private var phoneList:Array;
private var popupMenu:FlexNativeMenu;
private var lblWidth:uint;

private function init():void {
lblWidth = 50;
phoneList = new Array({type:"Home", number:"11111"}, {type:"Work", number:"22222"});
initPopupMenu();
phoneList.forEach(showPhoneList);
}

private function initPopupMenu():void {
popupMenu = new FlexNativeMenu();
popupMenu.dataProvider = defaultPhoneProps;
popupMenu.showRoot = false;
popupMenu.labelField = "@label";
}

private function showPhoneList(item:*, index:int, arr:Array):void {
var phoneLabel:Label = new Label();
var phoneNumber:TextInput = new TextInput();
var hBox:HBox = new HBox();
phoneLabel.id = "label";
phoneLabel.addEventListener(MouseEvent.CLICK, showContextMenu)
phoneLabel.text = item.type;
phoneLabel.width = lblWidth;
phoneNumber.id = "number";
phoneNumber.text = item.number;
hBox.id = "phone_"+item.type;
hBox.addChild(phoneLabel);
hBox.addChild(phoneNumber);
phoneListContainer.addChild(hBox);
}

private function showContextMenu(event:MouseEvent):void {
// Update Dataprovider
// Any changes to the dataprovider result in runtime error:
/*
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mx.controls::FlexNativeMenu/itemSelectHandler()[E:\dev\3.1.0\frameworks\projects\airframework\src\mx\controls\FlexNativeMenu.as:1633]
at flash.display::NativeMenu/_display()
at flash.display::NativeMenu/display()
at mx.controls::FlexNativeMenu/display()[E:\dev\3.1.0\frameworks\projects\airframework\src\mx\controls\FlexNativeMenu.as:1364]
at NativeMenuTest/showContextMenu()[C:\Users\Tushar\Documents\Flex Builder 3\NativeMenuTest\src\NativeMenuTest.mxml:56]
*/
// For example, you update the dataprovider:
for each (var property:XML in defaultPhoneProps..menuitem) {
property.@toggled = "false";
property.@enabled = "true";
}
defaultPhoneProps..menuitem.(@label==event.currentTarget.text).@toggled = "true";
defaultPhoneProps..menuitem.(@label==event.currentTarget.text).@enabled = "false";
// Show Popup Menu
popupMenu.addEventListener(FlexNativeMenuEvent.ITEM_CLICK, onItemClick);
popupMenu.display(event.target.stage, event.stageX, event.stageY);
}

private function onItemClick(menuEvent:FlexNativeMenuEvent):void{
popupMenu.removeEventListener(FlexNativeMenuEvent.ITEM_CLICK, onItemClick);
//Alert.show(menuEvent.item.@label, "Native Menu Event")
}
]]>
</mx:Script>
<mx:XML id="defaultPhoneProps" format="e4x">
<menu label="Popup">
<menuitem label="Work" command="toggleIconMenu"
type="check" toggled="false" enabled="true"/>
<menuitem label="Home" command="toggleMenuBar"
type="check" toggled="false" enabled="true"/>
<menuitem label="Mobile" command="toggleIconMenu"
type="check" toggled="false" enabled="true"/>
<menuitem label="HomeFax" command="toggleIconMenu"
type="check" toggled="false" enabled="true"/>
<menuitem label="WorkFax" command="toggleIconMenu"
type="check" toggled="false" enabled="true"/>
</menu>
</mx:XML>
<mx:VBox id="phoneListContainer" />
</mx:WindowedApplication>

Solution:
To solve this problem I had to work with the FlexNativeMenuItem directly.
Updated showContextMenu function:

private function showContextMenu(event:MouseEvent):void {
// Update NativeMenuItem directly along with the dataprovider
for each (var property:NativeMenuItem in popupMenu.nativeMenu.items) {
if(property.label == event.currentTarget.text){
property.enabled = false;
property.checked = true;
} else {
property.enabled = true;
property.checked = false;
}
}
// Show Popup
popupMenu.addEventListener(FlexNativeMenuEvent.ITEM_CLICK, onItemClick);
popupMenu.display(event.target.stage, event.stageX, event.stageY);
}

When for a list control the property editable is set to true, one can click on the item and rename the label or edit the item if an item editor is set. Here is a work around if you wish to enable editing only on double-click:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init();">

<mx:Script>
<![CDATA[

import mx.events.ListEvent;
import mx.core.EventPriority;

private function init():void {
myList.addEventListener(ListEvent.ITEM_DOUBLE_CLICK, onItemDoubleClick, 
			false, EventPriority.DEFAULT_HANDLER);
myList.addEventListener(ListEvent.ITEM_EDIT_END, onItemEditEnd, 
			false, EventPriority.DEFAULT_HANDLER);
}

private function onItemDoubleClick(event:ListEvent):void {
if (event.itemRenderer.data == "One") {
return;
}
if (event.isDefaultPrevented()) {
return;
}
myList.editable = true;
myList.editedItemPosition = {columnIndex:0, rowIndex:event.rowIndex};
}

private function onItemEditEnd(event:ListEvent):void {
myList.editable = false;
}
]]>
</mx:Script>

<mx:ArrayCollection id="myData">
<mx:String>One</mx:String>
<mx:String>Two</mx:String>
<mx:String>Three</mx:String>
<mx:String>Four</mx:String>
</mx:ArrayCollection>

<mx:Label text="Doubleclick any item to edit…"/>
<mx:List id="myList" doubleClickEnabled="true" dataProvider="{myData}" width="200"/>

</mx:Application>

Click here for live example.

Let me know incase of any bugs…

Posted by: Tushar | May 21, 2008

MXML ActionScript Classes

As you know, all MXML files are converted to ActionScript Classes which are later compiled in SWF file. If you want to view / study these automatically generated classes, you can use Compiler Argument -keep-generated-actionscript in Flex Builder Project.

In Flex Builder navigate to Project > Properties > Flex Compiler > Additional compiler arguments and add following configuration: -keep-generated-actionscript

This will create a folder named generated in project source folder which will have all ActionScript classes which Flex Builder automatically generates from MXML ({MXML file name}-generated).

Posted by: Tushar | May 15, 2008

Flex – Image Navigator Example

Image Navigator

Here is a small example of creating an Image Navigator for big images in Flex.

The big image is loaded in Canvas and an Image navigator will have a small prototype of this image. A small rectangle in Navigator can be used to scroll image. Click and drag small rectangle to scroll image. This rectangle corresponds to visible area of image in Canvas.

This example demonstrates usage of:

Image control

SWFLoader

Creating Sprite at runtime

Assigning Drag and drop functionality to sprite

Copying image using BitmapData

Controlling Scrollbar using ActionScript

Handling mouse events in Flex

Example: http://tushar.x10hosting.com/ImageNavigator/

Source: http://tushar.x10hosting.com/ImageNavigator/src/Navigator.mxml

Here is a very simple example of two way communication with database using Flex and PHP. In this example, we are sending username and password to the PHP file from Flex. PHP file then validates the input and returns the appropriate response.

This example also demonstrates the simple PHP script to establish a database (MySQL) connection and validate username and password against the table in database.

In AS3, we can use flash.net.URLLoader, URLRequest and URLVariables class to send and load data. First create a class named SendAndLoadExample.

Class SendAndLoadExample:

package {

import flash.events.*
import flash.net.*;

public class SendAndLoadExample {

public function SendAndLoadExample() {}
public function sendData(url:String, _vars:URLVariables):void {
var request:URLRequest = new URLRequest(url);
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
request.data = _vars;
request.method = URLRequestMethod.POST;
loader.addEventListener(Event.COMPLETE, handleComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.load(request);
}
private function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
trace("Par: " + loader.data.par);
trace("Message: " + loader.data.msg);
}
private function onIOError(event:IOErrorEvent):void {
trace("Error loading URL.");
}
}
}

Now, create an object of SendAndLoadExample class in Flex.

SendAndLoadExample.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
		layout="vertical">
<mx:Script>
<![CDATA[
import flash.net.URLVariables;
private var mySendAndLoadExample:SendAndLoadExample;
mySendAndLoadExample = new SendAndLoadExample();
private function sendAndLoad():void {
var url:String = "http://[your server]/login.php";
var variables:URLVariables = new URLVariables();
variables.UserName = "tushar";
variables.Password = "my_password";
mySendAndLoadExample.sendData(url, variables);
}
]]>
</mx:Script>
<mx:Button label="Fetch data" click="sendAndLoad()"/>
</mx:Application> 

PHP Script for login check: login.php

<?   
$clientUserName=$_POST['UserName'];   
$clientPassword=$_POST['Password'];   
//////////////////////////////////////   
// Host name   
$host="[your server]"; 
// Mysql username
$username="[MySql database username]"; 
// Mysql password     
$password="[MySql database password]"; 
// Database name    
$db_name="[MySql database name]"; 
// Table name  
$tbl_name="[MySql table name having usernames and passwords]";  
function makeConnection() {   
// Connect to server and select databse.   
mysql_connect("$GLOBALS[host]", "$GLOBALS[username]", 
		"$GLOBALS[password]")or die("cannot connect");   
mysql_select_db("$GLOBALS[db_name]")or die("cannot select DB");   
}   
function fireQuery($query) {   
$result=mysql_query($query);   
return $result;   
}   
function printOutput($code, $msg){   
print "par=$code&msg=$msg";   
}   
//////////////////////////////////////   
function checkUserID($id, $password) {   
$sql="SELECT * FROM $GLOBALS[tbl_name] WHERE 
		userName='$id' and password='$password'";   
$result=fireQuery($sql);   
$count=mysql_num_rows($result);   
if($count==1){   
return true;   
}   
return false;   
}   
function init(){   
if(isSet($GLOBALS["clientUserName"]) 
	&& isSet($GLOBALS["clientPassword"])){   
makeConnection();   
if(checkUserID($GLOBALS["clientUserName"]
	, $GLOBALS["clientPassword"])){   
printOutput("1", "Login successful.");   
} else {   
printOutput("0", "Failed to login $GLOBALS[clientUserName].");   
}   
} else {   
printOutput("0", "Required parameters missing.");   
}   
}   
init();   
?> 

However, you can also use HTTPService to send and load data in Flex. Nitin has posted a simple example of using HTTPService in flex. Check it out here.

Creating custom event handlers in ActionScript 3 is pretty much simple. Here is a simple example which loads an image and fires a custom event named “onImageLoad” as soon as image is loaded.

Class imageLoader.as

package {
import flash.events.*;
import flash.net.URLRequest;
import flash.display.Loader;
import flash.display.Sprite;
public class imageLoader extends EventDispatcher {
private var _mc:Sprite;
private var url:String;
private var loader:Loader;
public function imageLoader(_mc:Sprite, url:String) {
this._mc = _mc;
this.url = url;
loadImg();
_mc.addChild(loader);
}
private function loadImg():void {
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
var request:URLRequest = new URLRequest(url);
loader.load(request);
}
private function onComplete(event:Event):void {
dispatchEvent(new Event("onImageLoad"));
}
private function onIOError(event:IOErrorEvent):void {
trace("IO Error.");
}
}
}

Now in Flash, create a a object of imageLoader class and add a event listener (for our custom event “onImageLoad”).

var myImageLoader:imageLoader = new imageLoader(this, "images/someImg.jpg");
myImageLoader.addEventListener("onImageLoad", callbackHandler);
function callbackHandler(event:Event) {
trace("Image Loading Complete!");
}

Now test the file. Be sure to have someImg.jpg in images folder. Once image is loaded, you should be able to see “”Image Loading Complete!” message in output window.

In previous article “Component and SharedObject Example” we’ve seen how to store simple variables in Local Shared Object. But, what if you want to store a custom class objects in Shared Object?

You can use flash.net. registerClassAlias() to do so. This method is similar to old Object.registerClass() (Removed in AS3).

Shared Objects are stored in AMF (Action Message Format) format. When you try to save class object in Shared Object, it will be stored as normal object. It will not have any reference to the class. Thus to save the information about the class, one has to use registerClassAlias class. This is also called as Serializing Classes.

Apart from SharedObject, this class can be used for LocalConnection, ByteArray , NetConnection and NetStream.

Here is a simple example of using registerClassAlias. In this example, object of Person class is stored in Shared Object. This example also demonstrates use of AS3 components (Label, ComboBox, Button, InputText).

AS3 Serializing example image

Below is the code:

Class Person:

package {
public class Person {
private var _name:String;
private var _age:uint;
private var _gender:String;
public function Person() {
this._name = "";
this._age = undefined;
this._gender = "";
}
public function get name():String {
return this._name;
}
public function set name(name:String):void {
this._name = name;
}
public function get age():uint {
return this._age;
}
public function set age(age:uint):void {
this._age = age;
}
public function get gender():String {
return this._gender;
}
public function set gender(gender:String):void {
this._gender = gender;
}
public function getPerson():String {
return "Name: " + this._name + " Age: " + this._age + " Gender: " + this._gender;
}
}
}

Class soExample:

package {
import fl.controls.Button;
import fl.controls.Label;
import fl.controls.TextInput;
import fl.controls.NumericStepper;
import fl.controls.ComboBox;
import fl.data.DataProvider;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.SharedObject;
import flash.net.registerClassAlias;
public class soExample extends Sprite {
private var getData_btn:Button;
private var setData_btn:Button;
private var delData_btn:Button;
private var titleLbl:Label;
private var statLbl:Label;
private var nameLbl:Label;
private var ageLbl:Label;
private var genderLbl:Label;
private var name_txt:TextInput;
private var ageNS:NumericStepper;
private var genderCB:ComboBox;
private var _mc:Sprite;
private var mySO:SharedObject;
private var tushar:Person;
public function soExample(_mc:Sprite) {
registerClassAlias(”PersonAlias”, Person);
this._mc = _mc;
updateUI();
updateDisplay();
getSO();
}
private function updateUI():void {
getData_btn = createButton("Get Shared Object", 150, 10, 160, "get_btn");
setData_btn = createButton("Store Shared Object", 150, 10, 190, "set_btn");
delData_btn = createButton("Delete Shared Object", 150, 10, 220, "del_btn");
titleLbl = createLabel("<b>AS3 - Shared Object Example</b>", 200, 10, 10);
statLbl = createLabel("", 400, 10, 250);
nameLbl = createLabel("Name: ", 100, 10, 50);
ageLbl = createLabel("Age: ", 100, 10, 80);
genderLbl = createLabel("Gender: ", 100, 10, 110);
name_txt = createTextInput(200, 60, 50);
ageNS = createNumericStepper(25, 50, 22, 60, 80);
genderCB = createComboBox(100, 22, 60, 110, new DataProvider(["Male", "Female"]));
}
private function updateDisplay():void {
_mc.addChild(titleLbl);
_mc.addChild(nameLbl);
_mc.addChild(ageLbl);
_mc.addChild(genderLbl);
_mc.addChild(statLbl);
_mc.addChild(getData_btn);
_mc.addChild(setData_btn);
_mc.addChild(delData_btn);
_mc.addChild(ageNS);
_mc.addChild(name_txt);
_mc.addChild(genderCB);
}
private function createButton(lbl:String, w:uint, x:uint, y:uint, nme:String):Button {
var BTN:Button = new Button();
BTN.label = lbl;
BTN.width = w;
BTN.move(x, y);
BTN.name = nme;
BTN.addEventListener(MouseEvent.CLICK, clickHandler);
return BTN;
}
private function createLabel(lbl:String, w:uint, x:uint, y:uint):Label {
var LBL:Label = new Label();
LBL.htmlText = lbl;
LBL.width = w;
LBL.move(x, y);
return LBL;
}
private function createTextInput(w:uint, x:uint, y:uint):TextInput {
var TI:TextInput = new TextInput();
TI.htmlText = "";
TI.width = w;
TI.move(x, y);
return TI;
}
private function createNumericStepper(defaultVal:uint, w:uint, h:uint, x:uint, y:uint):NumericStepper {
var NS:NumericStepper = new NumericStepper();
NS.move(x, y);
NS.setSize(w, h);
NS.minimum = 1;
NS.maximum = 150;
NS.stepSize = 1;
NS.value = defaultVal;
return NS;
}
private function createComboBox(w:uint, h:uint, x:uint, y:uint, _data:DataProvider):ComboBox {
var CB:ComboBox = new ComboBox();
CB.move(x, y);
CB.setSize(w, h);
CB.dataProvider = _data;
return CB;
}
private function clickHandler(event:MouseEvent):void {
respondToMouseEvent(event.target.name);
}
private function respondToMouseEvent(nme:String):void {
switch (nme) {
case "get_btn":
getSO();
break;
case "set_btn":
setSO();
break;
case "del_btn":
deleteSO();
break;
}
}
private function getSO():void {
name_txt.text = "";
mySO = SharedObject.getLocal(”person”);
if (mySO.size == 0) {
// Shared object doesn’t exist.
statLbl.htmlText = "Status: SharedObject not found.";
name_txt.text = "";
ageNS.value = 25;
genderCB.selectedIndex = 0;
} else {
name_txt.text = mySO.data.person.name;
ageNS.value = mySO.data.person.age;
if(mySO.data.person.gender == "Female"){
genderCB.selectedIndex = 1;
}
statLbl.htmlText = "Status: SharedObject value is - <b>"+mySO.data.person.getPerson()+"</b>";
}
}
private function setSO():void {
if (name_txt.text != "") {
tushar = createPerson(name_txt.text, ageNS.value, genderCB.selectedItem.data);
mySO.data.person = tushar;
mySO.flush();
getSO();
} else {
statLbl.htmlText = "Status: <b>Name</b> missing.";
}
}
private function deleteSO():void {
mySO.clear();
getSO();
}
private function createPerson(name:String, age:uint, gender:String):Person {
var tmpPerson = new Person();
tmpPerson.name = name;
tmpPerson.age = age;
tmpPerson.gender = gender;
return tmpPerson;
}
}
}

Now, create object of soExample and pass movieclip reference (in which all the components will be added at runtime) as parameter:

var mySoExample:soExample = new soExample(this);

Note: Be sure to add “Button”, “Label”, “ComboBox”, “NumericStepper” & “TextInput” components to the library of that movie.

Source:  AS3 Serializing Example (Zip file included)

Older Posts »

Categories

Follow

Get every new post delivered to your Inbox.