How to Convert String into ArrayCollection in Flex? - apache-flex

Actually my Flex Application ..Sample code
private var selectedDays:String = null;
protected function selectRepeatedDays(event:MouseEvent):void
{
selectedDays = new String();
if(MON.selected==true)
{
selectedDays += "MONDAY,";
Alert.show("Monday :"+selectedDays);
}
if(TUE.selected==true)
{
selectedDays += "TUESDAY,";
}
if(WED.selected==true)
{
selectedDays += "WEDNESDAY,";
Alert.show("Monday :"+selectedDays);
}
if(THU.selected==true)
{
selectedDays += "THURSDAY,";
}
}
var arr:ArrayCollection = new ArrayCollection();
arr = selectedDays.substr(0, selectedDays.length-1).toString();
Alert.show(arr.lenth)
But it is not convert... the Alert Statement Not Prompt ..
So How to Convert This String into ArrayCollection...

Use the method split to convert the String to Array:
var array:Array = selectedDays.split(",");
Then (if needed yet) add each item of Array to the ArrayCollection:
var arr:ArrayCollection = new ArrayCollection();
for each (var str:String in array) {
arr.addItem(str);
}

use below code snippet to convert String to ArrayCollection
Convert String to Array using split method
var array:Array = selectedDays.split(",");
Convert Array to ArrayCollection
var selectedDaysArr:ArrayCollection = new ArrayCollection(array);

Related

Remove duplicate values from arraycollection in flex4

This is my arraycollection
o = JSON.parse(event.result.toString());
jsonarray = new ArrayCollection(o as Array);
in this array i have a duplicate values of product name, so i wants to remove duplicacy.\
my code is here,its not working please let me know, i am a flex beginner. thanx in advance.
function removeDuplicates(item:Object):Boolean
{
var returnValue:Boolean = false;
if (!myObject.hasOwnProperty(item.ProductName))
{
myObject[item.ProductName] = item;
returnValue = true;
}
prodArray.push(myObject);
return returnValue;
}
Call the filterCollection method given below and in that use the filterfunction to remove duplicates
private var tempObj:Object = {};
private function filterCollection():void {
// assign the filter function
jsonarray.filterFunction = removeDuplicates;
//refresh the collection
jsonarray.refresh();
}
private function removeDuplicates(item:Object):Boolean {
return (tempObj.hasOwnProperty(item.ProductName) ? false : tempObj[item.ProductName] = item && true);
}

Looping through an arraylist sourced from an XML file

I am reading in an XML file that is shown in the attached image. I'm reading it in using URLRequest, which works properly. The next thing I'd like to do is to populate an arraylist with all of the "project" nodes. I'm converting the XML to an array, but the source is showing the project as being in the [0] node and the arraylist's length is 1.
What's the proper way to do this so I can loop through all the projects in the arraylist?
private var xmlParameters:XML
private var xmlStoryMap:XMLList;
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
var params:Object;
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, xmlloader_onComplete_Handler);
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,IOError_handler);
xmlLoader.load(new URLRequest("myXML.xml"));
}
protected function xmlloader_onComplete_Handler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target)
xmlParameters = new XML(loader.data);
xmlStoryMap = xmlParameters.projects;
initializeMap();
}
protected function initializeMap():void
{
var testlist:ArrayList = new ArrayList();
testlist.source = convertXMLtoArray(xmlStoryMap.project);
}
private function convertXMLtoArray(file:String):Array
{
var xml:XMLDocument = new XMLDocument(file);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder;
var data:Object = decoder.decodeXML(xml);
var array:Array = ArrayUtil.toArray(data);
return array;
}
If you don't want to have a loop issue, use this instead
protected function xmlloader_onComplete_Handler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target)
var xmlString:String = loader.data;
initializeMap(xmlString);
}
protected function initializeMap(xmlString:String):void
{
var testlist:ArrayList = new ArrayList();
testlist.source = convertXMLtoArray(xmlString);
}
private function convertXMLtoArray(xmlString:String):Array
{
var xmlDoc:XMLDocument = new XMLDocument(xmlString);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder();
var data:Object = decoder.decodeXML(xmlDoc);
return ArrayUtil.toArray(data.storymap.projects.project);
}
For looping through the projects,
for each(var projectXML:XML in xmlParameters.projects.project)
{
// Do operation
}

Flex sort array collection by inner class

I want to sort an array collection in a way that I am not sure is possible.
Usually when you want to sort you have something like this.
var dataSortField1:SortField = new SortField();
dataSortField1.name = fieldOneToSortBy;
dataSortField1.numeric = fieldOneIsNumeric;
var dataSort:Sort = new Sort();
dataSort.fields = [dataSortField1];
arrayCollection.sort = dataSort;
arrayCollection.refresh();
so if I had a class
public class ToSort {
public var int:a
}
I could type
var ts1:ToSort = new ToSort();
ts1.a = 10;
var ts2:ToSort = new ToSort();
ts2.a = 20;
var arrayCollection:ArrayCollection = new ArrayCollection([ts1, ts2])
var dataSortField1:SortField = new SortField();
dataSortField1.name = "a";
dataSortField1.numeric = true;
var dataSort:Sort = new Sort();
dataSort.fields = [dataSortField1];
arrayCollection.sort = dataSort;
arrayCollection.refresh();
This works fine. My problem is I now have inherited a class that has another class inside it and I need to sort against this as well.
For example
public class ToSort2 {
public var int:a
public var ToSortInner: inner1
}
public class ToSortInner {
public var int:aa
public var int:bb
}
if a is the same in multiple classes then I want to sort on ToSortInner2.aa Is this possible. I have tried to pass in inner1.aa as the sort field name but this does not work.
Hope this is clear. If not I'll post some more code.
Thanks
You need to write a custom sort compareFunction. You can drill down into the objects properties inside the function.
Conceptually something like this:
public function aSort(a:Object, b:Object, fields:Array = null):int{
if(a.aa is b.aa){
return 0
} else if(a.aa > b.aa) {
return 1
} else{
return -1
}
}
When you create your sort object, you can specify the compare function:
var dataSort:Sort = new Sort();
dataSort.compareFunction = aSort;
arrayCollection.sort = dataSort;
arrayCollection.refresh();
Sort also has another property, compareFunction.

load multiple flv videos using FileReferenceList class

following is my code for loading one video using FileReference class and it works fine
[Event(name="complete",type="flash.events.Event")]
[Event(name="status",type="flash.events.StatusEvent")]
public class LocalFileLoader extends EventDispatcher
{
public function LocalFileLoader()
{}
private var file:FileReference;// = FileReference(event.target);
private var list:FileReferenceList;
public var p2pSharedObject:P2PSharedObject = new P2PSharedObject();
public function browseFileSystem():void {
file = new FileReference();
list = new FileReferenceList();
list.addEventListener(Event.SELECT, selectHandler);
list.browse();
}
protected function selectHandler(event:Event):void {
for each ( file in list.fileList ){
file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
file.addEventListener(Event.COMPLETE, completeHandler);
writeText(file.name+" | "+file.size);
file.load();
}
}
protected function securityErrorHandler(event:SecurityErrorEvent):void {
writeText("securityError: " + event);
}
protected function completeHandler(event:Event):void {
writeText("completeHandler");
p2pSharedObject = new P2PSharedObject();
p2pSharedObject.size = file.size;
p2pSharedObject.packetLength = Math.floor(file.size/32000)+1;
p2pSharedObject.data = file.data;
p2pSharedObject.chunks = new Object();
var desc:Object = new Object();
desc.totalChunks = p2pSharedObject.packetLength+1;
desc.name = file.name;
p2pSharedObject.chunks[0] = desc;
for(var i:int = 1;i<p2pSharedObject.packetLength;i++){
p2pSharedObject.chunks[i] = new ByteArray();
p2pSharedObject.data.readBytes(p2pSharedObject.chunks[i],0,32000);
}
// +1 last packet
p2pSharedObject.chunks[p2pSharedObject.packetLength] = new ByteArray();
p2pSharedObject.data.readBytes(p2pSharedObject.chunks[i],0,p2pSharedObject.data.bytesAvailable);
p2pSharedObject.packetLength+=1;
writeText("----- p2pSharedObject -----");
writeText("packetLenght: "+(p2pSharedObject.packetLength));
dispatchEvent(new Event(Event.COMPLETE));
}
protected function writeText(str:String):void{
var e:StatusEvent = new StatusEvent(StatusEvent.STATUS,false,false,"status",str);
dispatchEvent(e);
}
}
the sender.mxml code is following which plays the video on the stage
private function init() : void {
fileLoader = new LocalFileLoader();
fileLoader.addEventListener(Event.COMPLETE, fileLoaded);
fileShare = new P2PFileShare();
fileShare.addEventListener(StatusEvent.STATUS,
function(event:StatusEvent):void {
writeText(event.level);
});
fileShare.connect();
}
private function fileLoaded ( event:Event ) : void {
writeText("fileLoaded");
if (fileShare.connected) {
fileShare.p2pSharedObject = fileLoader.p2pSharedObject;
fileShare.p2pSharedObject.lastIndexBegin = 0;
fileShare.p2pSharedObject.lastIndexEnd = fileShare.p2pSharedObject.packetLength-1;
fileShare.updateHaveObjects();
}
setupVideo();
// PLAY
ns.play(null);
ns.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
ns.appendBytes(fileLoader.p2pSharedObject.data);
video.attachNetStream(ns);
}
private function setupVideo():void{
var nc:NetConnection = new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
ns.client = this;
ns.addEventListener(NetStatusEvent.NET_STATUS,
function(event:NetStatusEvent):void{
writeText("stream: "+event.info.code);
});
video = new Video();
videoComp = new UIComponent();
videoComp.addChild(video);
this.addElement(videoComp);
}
then after this, the file.name and file.size goes to mxml page and the video is displayed on stage with name and file size
but the samething i want to do with FileReferenceList class, i am solving this problem from last 2 weeks but cant ,,, plz guide me ,,, i google so many times but no specific answer
Regards
Ammad Khan
You can use the fileList property of the FileReferenceList class to access the files that where selected. Then load() each FileReference in the list separately:
private var list:FileReferenceList;
public function browseFileSystem():void {
list = new FileReferenceList();
list.addEventListener(Event.SELECT, selectHandler);
list.browse();
}
protected function selectHandler(event:Event):void {
for each ( var file:FileReference in list.fileList) {
file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
file.addEventListener(Event.COMPLETE, completeHandler);
writeText(file.name+" | "+file.size);
file.load();
}
}

Doubt in action script for Flex: getting unique elements from an ArrayCollection

I have an ArrayCollection as mentioned below.
private var initDG:ArrayCollection = new ArrayCollection([
{fact: "Order #2314", appName: "AA"},
{fact: "Order #2315", appName: "BB"}
{fact: "Order #2316", appName: "BB"}
...
{fact: "Order #2320", appName: "CC"}
{fact: "Order #2321", appName: "CC"}
]);
I want to populate a ComboBox with UNIQUE VALUES of "appName" field from the ArrayCollection initDG.
<mx:ComboBox id="appCombo" dataProvider="{initDG}" labelField="appName"/>
One method I could think is to loop through the Array objects and for each object check and push unique appName entries into another Array. Is there any better solution available?
That sounds good to me:
var unique:Object = {};
var value:String;
var array:Array = initDG.toArray();
var result:Array = [];
var i:int = 0;
var n:int = array.length;
for (i; i < n; i++)
{
value = array[i].appName;
if (!unique[value])
{
unique[value] = true;
result.push(value);
}
}
return new ArrayCollection(result);
You can used this class for finding unique arraycollection:
tempArray=_uniqueArray.applyUnqiueKey1(_normalsearchdata.toArray());
"uniqueArray" this is package name and _normalsearchdata is ArrayCollection;
package{
import mx.collections.ArrayCollection;
public class applyUniqueKey{
private var tempArray:Array;
private var tempIndex = 0;
public var temp:String;
public function applyUnqiueKey1(myArray)
{
tempArray = new Array();
tempIndex = 0;
myArray.sort();
tempArray[0] = myArray[0];
tempIndex++;
for(var i=1; i<myArray.length; i++) {
if(myArray[i] != myArray[i-1]) {
tempArray[tempIndex] = myArray[i];
tempIndex++;
}
}
var temp=String(tempArray.join());
return new ArrayCollection(tempArray);
}
}
}
Alas, there is no unique() method in ActionScript's Array, but you can approximate it like this:
var names:Array = initDG.toArray().map(
function (e:Object, i:Number, a:Array):String {
return e.appName;
}
);
var uniqueNames:Array = names.filter(
function (name:String, i:Number, a:Array):Boolean {
// Only returns true for the first instance.
return names.indexOf(name) == i;
}
);
Note this happens to work because you are filtering strings, which are compared by value. This wouldn't be effective if you needed to filter arbitrary objects.

Resources