Flash to Focus on PC Browsing and Mobile Apps; Adobe to More Aggressively Contribute to HTML5

November 10, 2011 Leave a comment

So its official now…Flash for mobile is going for a huge stop …… read the full story here.

Advertisements
Categories: Flex

Creating Singleton class in AS 3.0

August 2, 2011 Leave a comment

How to create a singleton class? Here is an example.

Let’s say we have a normal class like “Cricketer”.

package components
{
	public class Car{

		private var _carName:String;
		private var _carColor:String;
		private var _carPrize:int;

		/**
		 * CONSTRUCTOR
		 */

		public function Car(){}

		/**
		 * GETTERS AND SETTERS
		 */

		public function get carName():String{return _carName;}
		public function set carName(value:String):void{_carName = value;}
		public function get carColor():String{return _carColor;}
		public function set carColor(value:String):void{_carColor = value;}
		public function get carPrize():int{return _carPrize;}
		public function set carPrize(value:int):void{_carPrize = value;}

	}
}

Now to make this class singleton, add following piece of code.

package components
{

	public class Car{

		private var _carName:String;
		private var _carColor:String;
		private var _carPrize:int;

		protected static var _instance:Car;

		//Making singlton
		public static function getInstance():Car
		{
			if (_instance == null)
			{
				_instance = new Car();
			}
			return _instance;
		}

		/**
		 * CONSTRUCTOR
		 */

		public function Car(){}

		/**
		 * GETTERS AND SETTERS
		 */

		public function get carName():String{return _carName;}
		public function set carName(value:String):void{_carName = value;}
		public function get carColor():String{return _lastName;}
		public function set carColor(value:String):void{_lastName = value;}
		public function get carPrize():int{return _carPrize;}
		public function set carPrize(value:int):void{_carPrize = value;}

	}
}

Let’s see how we can utilize this feature in our application.

protected function checkSinglton(event:FlexEvent):void
{
	// TODO Auto-generated method stub
	//A First Cricketer
	var car:Car = Car.getInstance();
	car.carName= "Tata Indigo Marina";
	car.carColor = "0xEBEBEB";
	car.carPrize = 570000;

	trace ("My First Car: "+car.carName + "having color of " + car.carColor + " which cost me around " + car.carPrize.toString());

	//A new cricketer ? or not ?
	var secondCricketer:Cricketer = Cricketer.getInstance();
	trace ("Second Cricketer : "+cricketer.firstName + " " +cricketer.lastName " " +cricketer.type);
}
Categories: Action Script 3.0 Tags: ,

Replacing Strings in AS 3.0 with Regex

July 21, 2011 Leave a comment

Here we are replacing a sub String with in a string using a RegEx.

var sampleString:String = "The big bug bit the little beetle, but the little beetle bit the big bug back.";

var pattern:RegExp = /little/gi;
sampleString = sampleString.replace(pattern, "Seattle");
trace(sampleString);

The resultant would be something like this.

The big bug bit the little beetle, but the Seattle beetle bit the big bug back

Encrypted Local Storage

July 7, 2011 Leave a comment

Using Encrypted Local storage for your AIR application has its own pros and cons. One should take enough care for which purpose it is being used. Although this feature is supported by most of the OS, still it is not available for the Mobile applications.

EncryptedLocalStore isSupported is the property you can use to check whether ELS is supported or not.

ELS is strongly recommended to use as a private cache for the application. It should conatain only those information which needs to be secured from other users of the system or for Application specific user information.

ELS data can get lost due to few reasons like

–         Change in the Publisher ID as a result of the update.

–         User could uninstall the application & delete the ELS data.

How to storr file inELS ?

I am initiating the process by clicking let’s say “save” button.

protected function saveButton_clickHandler( event:MouseEvent ):void
{
	resultLabel.text = "";
	EncryptedLocalStore.reset();

	var file : File = File.documentsDirectory;
	file.browseForOpen("Save file to Encrypted Location");
	file.addEventListener(Event.SELECT,saveFile);
}

Now the “saveFile” function will work after the file has been selected by the user.

The target property will give us the instance of the File class, selected by user. Next, it creates an instance of the FileStream class that will be used to stream the bytes from the file into a ByteArray. Next, the filename is stored because it will be used as the key for the Encrypted Local Store. Finally, the value is stored in the Encrypted Local Store.

protected function saveFile( event:Event ):void
{
	var file = File(event.target);
	var stream :FileStream = new FileStream();

	var fileData : ByteArray = new ByteArray();
	stream.open(file,FileMode.READ);
	stream.readBytes(fileData,0,file.size);
	stream.close();
	fileName = file.name;

	EncryptedLocalStore.setItem(fileName,fileData);

	resultLabel.text = "File saved to encrypted local store"
}

 

Handle nested ArrayCollection with ObjectHierarchicalData for Advance DataGrid

June 28, 2011 Leave a comment
package
{
	import flash.events.EventDispatcher;
	import mx.collections.IHierarchicalData;
	[DefaultProperty("source")]
	public class ObjectHierarchicalData extends EventDispatcher implements
		IHierarchicalData {
		private var _source:Object;
		public function ObjectHierarchicalData() {}
		/* in our simple system, only parents with their type set to
		'parent' can have children */
		public function canHaveChildren(node:Object):Boolean
		{
			return ( node.type == 'parent' );
		}
		/* for any given node, determine whether that node has any children by
		looking through all the other nodes for that node's ID as a parentTask */
		public function hasChildren(node:Object):Boolean
		{
			var obj:Object;
			for each( obj in source )
			{
				if( obj.parentTask == node.objId )
					return true;
			}
			return false;
		}
		/* for any given node, return all the nodes that are children of that
		node in an array */
		public function getChildren(node:Object):Object
		{
			var parentId:String = node.objId;
			var children:Array = [];
			var obj:Object;
			for each( obj in source )
			{
				if( obj.parentTask == parentId )
					children.push( obj );
			}
			return children;
		}
		public function getData(node:Object):Object
		{
			var obj:Object;
			var prop:String;
			for each( obj in source )
			{
				for each( prop in node )
				{
					if( obj[prop] == node[prop] )
						return obj;
					else
						break;
				}
			}
			return null;
		}
		/* we want to return every obj that is a root object, which
		in this case is going to be all nodes that have a parent node
		of '0' */
		public function getRoot():Object
		{
			var rootsArr:Array = [];
			var obj:Object;
			for each( obj in source )
			{
				if( obj.parentTask == "0" )
				{
					rootsArr.push( obj );
				}
			}
			return rootsArr;
		}
		public function getParent(node:Object):*
		{
			var obj:Object;
			for each( obj in source )
			{
				if( obj.parentTask == node.parentTask )
					return obj;
			}
			return null;
		}
		public function get source():Object
		{
			return _source;
		}
		public function set source( value:Object ):void
		{
			_source = value;
		}
	}
}
Categories: Uncategorized

Spark Datagrid in Mobile – Basics Part 1

June 21, 2011 6 comments

Here is the code created to use Spark DataGrid in Mobile application. The new Spark Datagrid gives so much freedom to a designer that it can revamp the entire look and feel of a datagrid. Although ADOBE discourages the use of Datagrid in Mobile application, I decided to give it a go just for exploring purpose.

Let’s jump on the example directly.

The Example is a Checklist for your day to day work. This article is the first installment of the entire series of Checklist application development. Here, I will add the contents in the datagrid at runtime which includes checkbox and a text.

Here, I have a mobile project with a Datagrid named “dgTaskGrid”.

<s:DataGrid id="dgTaskGrid" skinClass="skins.DatagridSkin"
					width="100%" height="100%"
					 verticalScrollPolicy="on" />

Let’s create an arrayCollection “taskItems” in the script part, which will be a Dataprovider for the Grid .

private var taskItems : ArrayCollection = new ArrayCollection();

In the declarations tab, I have a ArrayList named “checkList” which will have a two GridColumn child inside it.

<s:ArrayList id="checkList">
	<s:GridColumn width="50">
		<s:itemRenderer>
		<fx:Component>
			<s:GridItemRenderer textAlign="center" >
				<s:CheckBox label="" selected="{data.isFinished}" horizontalCenter="0"/>
			</s:GridItemRenderer>
			</fx:Component>
				</s:itemRenderer>
			</s:GridColumn>
			<s:GridColumn headerText=""
				  dataField="text"/>
		</s:ArrayList>

I have added checkbox component in the GridItemRenderer of the first column and second column will represent my text for the new task to be added.

I need to set the dataProvider and columns property of the grid “dgTaskGrid” to feed in the data. So updated Datagrid will have following code.

<s:DataGrid id="dgTaskGrid"
	    skinClass="skins.DatagridSkin"
	    width="100%" height="100%"
	    dataProvider="{taskItems}"
	    columns="{checkList}"
	    verticalScrollPolicy="on" />

If you look closely to my sample application, I am adding a row in the Datagrid at rumtime when I click the “Add” button. All I have to do is create an object which will include my new task text. Following is the code of the same.

protected function btnAddTask_clickHandler(event:MouseEvent):void
{
	var taskItem : Object = new Object();
	taskItem.text = txtTaskName.text;
	taskItem.isFinished = false;
	taskItems.addItem(taskItem);
	txtTaskName.text = "";
}

This includes pretty much everything to display the newly added task in the Datagrid.

Now, something about the styling part where I don’t want to show the usual look of the datagrid that includes the rows and columns.

For this purpose I have created a styleClass for the spark Datagrid where I have disable the following skin.

–        columnSeparator

–        rowSeparator

–        headerSeparator

Moreover, I  don’t have anything to show in the header part of the grid. So I am just setting the visible property of ”GridColumnHeaderGroup” to make it disappear.

That’s it. You can see how the application looks in the below screen shot when add a list of tasks to be completed.

 

 


								

ASyncToken and IResponder in Flex

June 20, 2011 1 comment

You want to call a set of Webservices one after another. A usual approach will be using result event of the first one to call the next one.

Well more better way of doing the same thing is using the Asynctocken and Responer interfaces which can track objects and pass parameters to the co-dependent services. Let’s have a sample.

For a demo purpose I am using following Dictionary Webservice.

http://services.aonaware.com/DictService/DictService.asmx

This Webservice gives an API for dictionary purpose. For quicker way, I am using wizard to call the webservice. Just add the wsdl and there you go.

Next step is to call the webservice function on creationComplete() event of the application.

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
			   creationComplete="application1_creationCompleteHandler(event)">
			private var dict : DictService = new DictService();
			private var token:AsyncToken;
			private var responder:mx.rpc.Responder;

			protected function application1_creationCompleteHandler(event:FlexEvent):void
			{
				// TODO Auto-generated method stub
				token = dict.DictionaryList();
				responder = new mx.rpc.Responder(onResult, onFault)
				token.addResponder(responder);

			}
			public function onResult(event:ResultEvent):void
			{

			}
			public function onFault(event:FaultEvent):void
			{

			}
		]]>
	</fx:Script>

	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx:Declarations>
</s:Application>