March 5, 2009
The code below demonstrates the data type conversions among basic DataTypes used most in Flex. The ‘init()’ method does to and from conversion for ArrayCollection to XML and XML to ArrayCollection
Object, String, XML, ArrayCollection
import mx.collections.ArrayCollection;
import mx.rpc.xml.SimpleXMLEncoder;
import mx.rpc.xml.SimpleXMLDecoder;
import mx.utils.ObjectUtil;
private function xmlToArrayCollection(xml:XML):ArrayCollection{
var xmlDoc:XMLDocument = new XMLDocument(xml.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
var ac:ArrayCollection =new ArrayCollection(Array(resultObj.root.list.source.item));
return ac;
}
private function objectToXML(obj:Object):XML {
var qName:QName = new QName(“root”);
var xmlDocument:XMLDocument = new XMLDocument();
var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
var xml:XML = new XML(xmlDocument.toString());
return xml;
}
private function objectToArrayCollection(obj:Object):ArrayCollection {
var ac:ArrayCollection = new ArrayCollection(obj as Array);
return ac;
}
private function arrayCollectionToXML(ac:ArrayCollection):XML{
var xml:XML = objectToXML(ac);
return xml;
}
private function init():void{
var arr:Array = new Array();
arr.push({data:0,name:’deva’});
arr.push({data:1,name:’raj’});
var ac:ArrayCollection = new ArrayCollection(arr);
var xml:XML = arrayCollectionToXML(ac);
var newAc:ArrayCollection = xmlToArrayCollection(xml);
trace(newAc[0][0].name);
}
private function objToStr(value:Object,indent:int =0,
refs:Dictionary= null,
namespaceURIs:Array = null,
exclude:Array = null):String{
var str:String;
var refCount:int = 0;
if (value is Date)
{
return value.toString();
}
else if (value is XMLNode)
{
return value.toString();
}
else if (value is Class)
{
return “(” + getQualifiedClassName(value) + “)”;
}
else
{
var classInfo:Object = ObjectUtil.getClassInfo(value, exclude,
{ includeReadOnly: true, uris: namespaceURIs });
var properties:Array = classInfo.properties;
str = “(” + classInfo.name + “)”;
if (refs == null)
refs = new Dictionary(true);
var id:Object = refs[value];
if (id != null)
{
str += “#” + int(id);
return str;
}
if (value != null)
{
str += “#” + refCount.toString();
refs[value] = refCount;
refCount++;
}
var isArray:Boolean = value is Array;
var isDict:Boolean = value is Dictionary;
var prop:*;
indent += 2;
for (var j:int = 0; j < properties.length; j++)
{
str = newline(str, indent);
prop = properties[j];
if (isArray)
str += “[";
else if (isDict)
str += "{";
if (isDict)
{
str += objToStr(prop, indent, refs,
namespaceURIs, exclude);
}
else
{
str += prop.toString();
}
if (isArray)
str += "] “;
else if (isDict)
str += “} = “;
else
str += ” = “;
try
{
str += objToStr(value[prop], indent, refs,
namespaceURIs, exclude);
}
catch(e:Error)
{
str += “?”;
}
}
indent -= 2;
return str;
}
}
private static function newline(str:String, n:int = 0):String
{
var result:String = str;
result += “\n”;
for (var i:int = 0; i < n; i++)
{
result += ” “;
}
return result;
}
/* General function for Conversion (thanks, Krystian Bień)
public function xmlToArrayCollection(xml:XML):ArrayCollection{
var temp:String = ‘<items>’ + xml.toString() + ‘</items>’;
xml = XML(temp);
var xmlDoc:XMLDocument = new XMLDocument(xml.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
var ac:ArrayCollection;
ac = new ArrayCollection();
ac.addItem(resultObj.items);
return ac;
}*/
2 Comments |
Flex | Tagged: ArrayCollection, ArrayCollection to XML, as3, convert, Datatype, Flex, Object to String, string, using, XML, xml to array, XML to ArrayCollection |
Permalink
Posted by nsdevaraj
September 8, 2008
The Below code is example for using IViewCursor for ArrayCollection Navigation
<?xml version=”1.0″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” initialize=”run();”>
<mx:Script>
<![CDATA[
import mx.collections.*;
private var myCursor:IViewCursor;
[Bindable]
public var myAC:ArrayCollection;
public var myArray:Array = [ { label:1, data:"One" }, { label:2, data:"Two" }, { label:3, data:"Three" }, { label:4, data:"Four" }, { label:5, data:"Five" },
{ label:6, data:"Six" }, { label:7, data:"Seven" }, { label:8, data:"Eight" }, { label:9, data:"Nine" }, {label:10, data:"Ten"}];
public function run():void {
myAC = new ArrayCollection(myArray);
myCursor=myAC.createCursor();
var sort:Sort = new Sort();
sort.fields = [new SortField("label")];
myAC.sort=sort;
myAC.refresh();
first.enabled = false;
back.enabled = false;
}
public function countLast(theCursor:IViewCursor):int {
var counter:int=0;
var mark:CursorBookmark=theCursor.bookmark;
while (theCursor.moveNext()) {
counter++;
}
theCursor.seek(mark);
return counter;
}
public function countFromSelection():void {
myCursor.findAny(myCB.selectedItem);
var count:int = countLast(myCursor);
ta1.text = “cursor is at: ” + myCursor.current.label;
enableDisableButtons();
}
public function nextCollection():void {
if(! myCursor.afterLast) {
myCursor.moveNext();
ta1.text=”cursor is at: ” + myCursor.current.label;
}
}
public function backCollection():void {
if(!myCursor.beforeFirst) {
myCursor.movePrevious();
ta1.text=”cursor is at: ” + myCursor.current.label;
}
}
public function firstCollection():void {
myCursor.seek(CursorBookmark.FIRST);
ta1.text=”cursor is at: ” + myCursor.current.label;
}
public function lastCollection():void {
myCursor.seek(CursorBookmark.LAST);
ta1.text=”cursor is at: ” + myCursor.current.label;
}
public function navigate(event:MouseEvent):void {
switch(event.currentTarget.label) {
case ‘first’:
firstCollection();
break;
case ‘back’:
backCollection();
break;
case ‘next’:
nextCollection();
break;
case ‘last’:
lastCollection();
break;
}
enableDisableButtons()
}
public function enableDisableButtons():void{
var firstInCollection:Boolean = myAC.getItemAt(0) == myCursor.current;
first.enabled = back.enabled = !firstInCollection
var lastInCollection:Boolean = myAC.getItemAt(myAC.length – 1) == myCursor.current;
last.enabled = next.enabled = !lastInCollection;
}
]]>
</mx:Script>
<mx:ComboBox id=”myCB” dataProvider=”{myAC}” change=”countFromSelection();”/>
<mx:TextArea id=”ta1″ height=”200″ width=”175″/>
<mx:HBox>
<mx:Button label=”first” id=”first” click=”navigate(event)”/>
<mx:Button label=”back” id=”back” click=”navigate(event)”/>
<mx:Button label=”next” id=”next” click=”navigate(event)”/>
<mx:Button label=”last” id=”last” click=”navigate(event)”/>
</mx:HBox>
</mx:Application>
Leave a Comment » |
Flex | Tagged: Adobe, ArrayCollection, as3, Back, Bookmark, Cursor, CursorBookmark, First, Flex, IViewCursor, Last, Navigation, Next, seek |
Permalink
Posted by nsdevaraj
August 20, 2008
This post have three significant solutions:
1. ArrayCollection output into XML
2. Converting any MySQL DB values into XML using PHP
3. Simple Login form using PHP and MXML
The below php code converts db output as xml dbtoxml.php
// <?php
// define(“HOSTNAME”,”localhost”);
// define(“USERNAME”,”root”);
// define(“PASSWORD”,”");
// define(“DB_NAME”,”users”);
// define(“TABLE_NAME”,”users”);
// mysql_connect(HOSTNAME, USERNAME, PASSWORD);
// mysql_select_db(DB_NAME);
// $result = mysql_query(“SELECT * FROM “.TABLE_NAME);//Get the number of rows
// $num_row = mysql_num_rows($result);
// echo ‘<?xml version=”1.0″ encoding=”iso-8859-1″?>’;//Start the output of XML
// echo “<data>”;
// echo ‘<num>’ .$num_row. ‘</num>’;
// if (!$result) {
// die(‘Query failed: ‘ . mysql_error());
// }
// /* get column metadata – column name */
// $i = 0;
// while ($i < mysql_num_fields($result)) {
// $meta = mysql_fetch_field($result, $i);
// $ColumnNames[] = $meta->name; //place col name into array
// $i++;
// }
// $specialchar = array(“&”,”>”,”<”); //special characters
// $specialcharReplace = array(“&”,”>”,”<”); //replacement
// /* query & convert table data and column names to xml*/
// $w = 0;
// while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// echo “<row>”;
// foreach ($line as $col_value){
// echo ‘<’.$ColumnNames[$w].’>’;
// $col_value_strip = str_replace($specialchar, $specialcharReplace, $col_value);
// echo $col_value_strip;
// echo ‘</’.$ColumnNames[$w].’>’;
// if($w == ($i – 1)) { $w = 0; }
// else { $w++; }
// }
// echo “</row>”;
// }
// echo “</data>”;
// mysql_free_result($result);
// ?>
The below mxml file converts php ArrayCollection output into XML dbconnect.mxml
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”horizontal” creationComplete=”dbconnect.send();”>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
import mx.collections.ArrayCollection;
public var XMLNodeObjXMLList:XMLList;
[Bindable] public var loggedIn:Boolean;
public function checkLogin():void {
var userName:String = userId.text;
var passWord:String = pwd.text;
var passList:XMLList = XMLNodeObjXMLList.record.(user == userName);
loggedIn = String(passList.pass) == passWord;
loggedIn ? Alert.show(‘Logged In’) : Alert.show(‘Try Again’);
}
private function resultHandler(e:ResultEvent):void {
XMLNodeObjXMLList = ObjToXmlList(e.result.data.row);
}
private function ObjToXmlList(XMLArrCol:ArrayCollection):XMLList {
var XMLStr:String = “<?xml version=\”1.0\” encoding=\”UTF-8\”?>\n<data>”;
for each(var XMLNodeObj:Object in XMLArrCol) {
XMLStr += “<record>”;
XMLStr += “<user>” + XMLNodeObj.user + “</user>”;
XMLStr += “<pass>” + XMLNodeObj.pass + “</pass>”;
XMLStr += “</record>”;
}
XMLStr += “\n</data>”;
return new XMLList(XMLStr);
}
]]>
</mx:Script>
<mx:HTTPService id=”dbconnect” showBusyCursor=”true” url=”http://localhost/dbtoxml.php” useProxy=”false” result=”resultHandler(event)” />
<mx:Form visible=”{!loggedIn}” includeInLayout=”{!loggedIn}”>
<mx:FormItem label=”Username : “> <mx:TextInput id=”userId” text=”deva” />
</mx:FormItem>
<mx:FormItem label=”Password : “>
<mx:TextInput id=”pwd” displayAsPassword=”true” text=”deva” />
</mx:FormItem>
<mx:FormItem>
<mx:Button label=”Login” click=”checkLogin()”/>
</mx:FormItem> </mx:Form>
<mx:HBox visible=”{loggedIn}” includeInLayout=”{loggedIn}”>
<mx:Label text=”Logged In”/>
</mx:HBox>
2 Comments |
Flex | Tagged: ArrayCollection, as3, Flex, Login, Login Form, mxml, MySQL, MySQL to XML, php |
Permalink
Posted by nsdevaraj