Finding previous word boundary with enter key? - apache-flex

This code works great and it get the last word, but when I use enter key
it behaves erroneously and stops getting last word(s). When I comment the findPreviousWordBoundary line, it gets all text:
<fx:Script>
<![CDATA[
import flashx.textLayout.elements.ParagraphElement;
protected function togglebutton1_clickHandler(event:MouseEvent):void {
var urlLoader:URLLoader = new URLLoader();
var suggestions:Array = new Array();
var suggested:Array = new Array();
var textfields:Array = new Array();
var format:TextFormat = new TextFormat();
var currentSelection:int = -1;
mytextflow.addEventListener(KeyboardEvent.KEY_UP, suggest);
function suggest(event:KeyboardEvent):void {
suggested = [];
var activePos:int = mytextflow.selectionActivePosition
var curParagraph:ParagraphElement =
mytextflow.textFlow.findLeaf(activePos).getParagraph();
var wordBoundary:int = curParagraph.
findPreviousWordBoundary(activePos);
//var lastword:String = curParagraph.getText(wordBoundary,activePos);
}
}
]]>
</fx:Script>
<s:ToggleButton x="21" y="10"
click="togglebutton1_clickHandler(event)"/>
<s:RichEditableText
id="mytextflow"
x="111"
y="43"
width="363"
height="285"
backgroundColor="#C39191"/>
</s:Application>

Related

newbie: flex netstream how to get my code stream and receive netstreams correctly?

I have problems getting my flex code to work, below is my code I try to netstream a webcam and receive it and use 2 functions for that. Any flex guru can help me fix these functions?
function onNetConnectionPublish():void {
StatusMessage("onNetConnectionPublish called");
ncNetStream = new NetStream(nc, NetStream.DIRECT_CONNECTIONS);
ncNetStream.addEventListener(NetStatusEvent.NET_STATUS, sendNetStreamHandler);
ncNetStream.publish("media");
ncNetStream.attachAudio(Microphone.getMicrophone());
ncNetStream.attachCamera(Camera.getCamera());
}
and:
function connectToRemote(remoteId:String) {
StatusMessage("connectToRemote(" + remoteId + ")");
ncNetStream = new NetStream(nc, remoteId);
ncNetStream.addEventListener(NetStatusEvent.NET_STATUS, receiveNetStreamHandler);
ncNetStream.play("media");
}
display video:
The Publisher Application:
private function Publisher():void{
var camera1:Camera = Camera.getCamera();
var video:Video = new Video(285, 254);
if (camera1)
{
video.attachCamera(camera1);
VideoDisplay1.addChild(video);
camera1.addEventListener(ActivityEvent.ACTIVITY, camera_activity);
camera1.addEventListener(StatusEvent.STATUS, camera_status);
}
var nc:NetConnection = new NetConnection();
nc.connect("rtmp://your/stream/url");
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
function netStatusHandler(event:NetStatusEvent):void {
switch (event.info.code) {
case "NetConnection.Connect.Success":
var ns:NetStream = new NetStream(nc,NetStream.CONNECT_TO_FMS);
ns.attachCamera(camera1);
ns.publish("videofeed", "live");
break;
case "NetStream.Play.StreamNotFound":
trace("Unable to locate video: ");
break;
}
}
}
The Reciever Application :
import mx.utils.ObjectUtil;
private var nc:NetConnection;
private var ns:NetStream;
private var video:Video;
private var meta:Object;
private function init():void {
var nsClient:Object = {};
nsClient.onMetaData = ns_onMetaData;
nsClient.onCuePoint = ns_onCuePoint;
nc = new NetConnection();
nc.connect(null);
ns = new NetStream(nc);
ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv");
ns.client = nsClient;
video = new Video();
video.attachNetStream(ns);
uic.addChild(video);
}
private function ns_onMetaData(item:Object):void {
trace("meta");
meta = item;
// Resize Video object to same size as meta data.
video.width = item.width;
video.height = item.height;
// Resize UIComponent to same size as Video object.
uic.width = video.width;
uic.height = video.height;
panel.title = "framerate: " + item.framerate;
panel.visible = true;
trace(ObjectUtil.toString(item));
}
private function ns_onCuePoint(item:Object):void {
trace("cue");
}
Reciever mxml code :
<mx:Panel id="panel" visible="false">
<mx:UIComponent id="uic" />
<mx:ControlBar>
<mx:Button label="Play/Pause" click="ns.togglePause();" />
<mx:Button label="Rewind" click="ns.seek(0); ns.pause();" />
</mx:ControlBar>
</mx:Panel>

Flex Android application suspends when using jpeg image

I have a flex application in which I have to convert a jpeg picture taken by camera using base64 converter and then upload the result to sqlite database (as MEDIUMBLOB). The code looks like this:
MXML declarations of images:
<s:Group width="480" height="304">
<s:Label x="0" y="0" width="100%" height="34" backgroundColor="#4D4D4D"
color="#FFFFFF" fontSize="30" text=" Select photo" verticalAlign="middle"/>
<s:Image id="image" x="10" y="42" width="217" height="246" />
<s:Image id="image2" x="10" y="42" width="217" height="246" source = "#Embed(source='skins/PhotoNotAvailable.jpg')"/>
<s:Button x="235" y="42" width="235" height="84" label="Take a Picture"
click="captureImage(event)" enabled="{CameraUI.isSupported}" fontSize="30"/>
<s:Button x="235" y="150" width="235" height="70" label="Delete"
click="deletePhoto(event)" fontSize="30"/>
</s:Group>
Scripts for taking a picture and convertion:
//Taking the pictures
protected function application1_applicationCompleteHandler(event:FlexEvent):void {
image.setVisible(true);
image2.setVisible(false);
if (CameraUI.isSupported){
var mediaPromise:MediaPromise;
camera = new CameraUI();
camera.addEventListener(MediaEvent.COMPLETE, onComplete);
camera.addEventListener(ErrorEvent.ERROR, onError);
} else {
}
}
protected function view1_activateHandler(event:Event):void
{
conn = data as SQLConnection;
}
private function captureImage(event:MouseEvent):void {
camera.launch(MediaType.IMAGE);
}
private function onError(event:ErrorEvent):void {
trace("error has occurred");
}
private function onComplete(event:MediaEvent):void {
var mediaPromise:MediaPromise = event.data;
image.source = mediaPromise.file.url;
pictureTaken = true;
}
//Convertion and uploading to database
protected function AddHandler(event:MouseEvent):void
//irrelevant code skipped
insertStmt = new SQLStatement();
insertStmt.sqlConnection = conn;
var insertSQL:String = ("INSERT INTO RecipeDB (RecipeID, Name, Category, Origin, Recipe, Favorite, Image)" + "VALUES (:RecipeID, :Name, :Category, :Origin, :Recipe, :Favorite, :Image)");
insertStmt.text = insertSQL;
if(pictureTaken)
{
var jencoder:JPEGEncoder = new JPEGEncoder(75);
var imageByteArray:ByteArray = jencoder.encode(image.bitmapData);
var baseEncoder:Base64Encoder = new Base64Encoder();
baseEncoder.encodeBytes(imageByteArray);
encodedBytes = baseEncoder.toString();
}
else
{
var jencoder:JPEGEncoder = new JPEGEncoder(75);
var imageByteArray:ByteArray = jencoder.encode(image2.bitmapData);
var baseEncoder:Base64Encoder = new Base64Encoder();
baseEncoder.encodeBytes(imageByteArray);
encodedBytes = baseEncoder.toString();
}
insertStmt.parameters[":RecipeID"] = ID as int;
insertStmt.parameters[":Name"] = NameArea.text;
insertStmt.parameters[":Category"] = TypeArea.text;
insertStmt.parameters[":Origin"] = OriginArea.text;
insertStmt.parameters[":Recipe"] = RecipeArea.text;
insertStmt.parameters[":Favorite"] = 0 as int;
insertStmt.parameters[":Image"] = encodedBytes;
insertStmt.execute();
}
//Deleting photo
protected function deletePhoto(event:MouseEvent):void
{
pictureTaken = false;
image.setVisible(false);
image2.setVisible(true);
}
Now, if no picture was taken, the program uploads skins/PhotoNotAvailable.jpg to the DB correctly, but if the picture was taken or taken and deleted, the program hangs (android asks if to close it or wait). I have checked the size of taken pictures and it does not exceed MEDIUMBLOB`s size (picture has ca. 2 MBytes). What could be wrong?
My first thought from your description of what happens is "a breakpoint." The only time my phone gives me that message is when I'm debugging and it's stopped on a break point for too long.
You might cast your event.data as MediaPromise
private function onComplete(event:MediaEvent):void {
var mediaPromise:MediaPromise = event.data as MediaPromise;
image.source = mediaPromise.file.url;
pictureTaken = true;
}
Though that may just be a copying error.
So far as I can tell you don't need to base64 encode the image data. It's already encoded and ready to be inserted into a database. Perhaps "double-encoding" is somehow creating a problem. ???
I would change
if(pictureTaken)
{
var jencoder:JPEGEncoder = new JPEGEncoder(75);
var imageByteArray:ByteArray = jencoder.encode(image.bitmapData);
var baseEncoder:Base64Encoder = new Base64Encoder();
baseEncoder.encodeBytes(imageByteArray);
encodedBytes = baseEncoder.toString();
}
else
{
var jencoder:JPEGEncoder = new JPEGEncoder(75);
var imageByteArray:ByteArray = jencoder.encode(image2.bitmapData);
var baseEncoder:Base64Encoder = new Base64Encoder();
baseEncoder.encodeBytes(imageByteArray);
encodedBytes = baseEncoder.toString();
}
insertStmt.parameters[":RecipeID"] = ID as int;
insertStmt.parameters[":Name"] = NameArea.text;
insertStmt.parameters[":Category"] = TypeArea.text;
insertStmt.parameters[":Origin"] = OriginArea.text;
insertStmt.parameters[":Recipe"] = RecipeArea.text;
insertStmt.parameters[":Favorite"] = 0 as int;
insertStmt.parameters[":Image"] = encodedBytes;
insertStmt.execute();
to
var jencoder:JPEGEncoder = new JPEGEncoder(75);
var imageByteArray:ByteArray;
if(pictureTaken)
{
imageByteArray = jencoder.encode(image.bitmapData);
}
else
{
imageByteArray = jencoder.encode(image2.bitmapData);
}
insertStmt.parameters[":RecipeID"] = ID as int;
insertStmt.parameters[":Name"] = NameArea.text;
insertStmt.parameters[":Category"] = TypeArea.text;
insertStmt.parameters[":Origin"] = OriginArea.text;
insertStmt.parameters[":Recipe"] = RecipeArea.text;
insertStmt.parameters[":Favorite"] = 0 as int;
insertStmt.parameters[":Image"] = imageByteArray;
insertStmt.execute();
If for some reason you still want the base64 encoding and it's not creating the problem, I would still suggest refactoring the code like this to save duplication since the only thing that varies between the two if branches is the source of the bitmap data.
var jencoder:JPEGEncoder = new JPEGEncoder(75);
var imageByteArray:ByteArray;
if(pictureTaken)
{
imageByteArray = jencoder.encode(image.bitmapData);
}
else
{
imageByteArray = jencoder.encode(image2.bitmapData);
}
var baseEncoder:Base64Encoder = new Base64Encoder();
baseEncoder.encodeBytes(imageByteArray);
encodedBytes = baseEncoder.toString();
However, this is just a first stab at it. It would be useful to see the code all together. I'm assuming that encodedBytes is a String available to the whole class? I can't see how/when AddHandler is invoked, so I also can't tell variable states when it is called (which could be related to the problem). It would also be useful to know what's happening after the AddHandler is completed. Perhaps it's an error occurring after the insert statement that is hanging up?
Did you debug it and get any errors to share?
I know the post is a month old, so maybe you already figured it out. Maybe you could share it so others don't make the same mistake. Either way, I hope this can help someone.

spark Text area height adjust to content

i want to adjust the size of my text area in action script based on the text i put inside dynamically, but absolutly don't know how to do that... searched a lot for nothing. Here is my code if it can help you situate the problem. I want to adjust the height of msgLabel to the content.
Thanks a lot ;).
public function createTweet(tweet:XML, lineName:String, isTweetInList:Boolean):IVisualElement{
var authorS:String = tweet.posterName;
var tweetID:String = tweet.tweetID;
//Main vertical group
var vg:VGroup = new VGroup();
vg.percentWidth = 100;
if(!isTweetInList){
//Add the new VGroup to the tweetTabHolder
tweetTabHolder[tweetID+lineName] = vg;
//Add the new tweetID to the tweet posted by an author
if(tweetByLineByAuthor[authorS] == null)
tweetByLineByAuthor[authorS] = new Dictionary();
if(tweetByLineByAuthor[authorS][lineName] == null)
tweetByLineByAuthor[authorS][lineName] = new ArrayList();
tweetByLineByAuthor[authorS][lineName].addItem(tweetID);
}
vg.setStyle("backgroundAlpha", 0);
vg.paddingLeft = 20;
var sp0:Spacer = new Spacer();
sp0.height = 10;
vg.addElement(sp0);
//Tweet Content
//Author
var hgA:HGroup = new HGroup();
var aSpacer:Spacer = new Spacer();
aSpacer.width = 10;
hgA.addElement(aSpacer);
var authorLabel:RichText = new RichText();
authorLabel.text = authorS;
authorLabel.setStyle("fontSize",20);
authorLabel.setStyle("fontWeight",FontWeight.BOLD);
authorLabel.setStyle("color",authorColor);
authorLabel.addEventListener("click",authorClickHandler);
authorLabel.addEventListener(MouseEvent.MOUSE_OVER,authorFocusInHandler);
authorLabel.addEventListener(MouseEvent.MOUSE_OUT,authorFocusOutHandler);
hgA.addElement(authorLabel);
if(tweet.posterName == userNameLogged || isTweetInList){
var abs1:Spacer = new Spacer();
abs1.width = 25;
hgA.addElement(abs1);
hgA.addElement(createDeleteTweetButton(tweetID,vg, isTweetInList));
var abs2:Spacer = new Spacer();
}
if(!isTweetInList){
abs2.width = 4;
hgA.addElement(abs2);
hgA.addElement(createFavorisButton(tweetID));
}
vg.addElement(hgA);
//Msg
var hgM:HGroup = new HGroup();
var mSpacer:Spacer = new Spacer();
mSpacer.width = 15;
hgM.addElement(mSpacer);
var msgLabel:TextArea = new TextArea();
hgM.addElement(msgLabel);
hgM.percentWidth = 100;
msgLabel.percentWidth = 100;
msgLabel.text = tweet.msg;
msgLabel.setStyle("fontSize",12);
msgLabel.setStyle("color",msgColor);
msgLabel.editable = false;
msgLabel.setStyle("lineBreak", "toFit");
vg.addElement(hgM);
//Date
var hgD:HGroup = new HGroup();
var dSpacer:Spacer = new Spacer();
dSpacer.width = 10;
hgD.addElement(dSpacer);
var dateLabel:Label = new Label();
dateLabel.text = tweet.postingDate.date;
dateLabel.setStyle("fontSize",10);
dateLabel.setStyle("color",dateColor);
hgD.addElement(dateLabel);
vg.addElement(hgD);
var sp1:Spacer = new Spacer();
sp1.height = 10;
vg.addElement(sp1);
var hr:HRule = new HRule();
hr.percentWidth = 90;
hr.x = 20;
vg.addElement(hr);
return vg;
}
First off, why are you using Actionscript when your application is clearly Flex? You could reduce that mess of code by 2/3. Also, last I checked they all resize to their content unless you specify their dimensions. Either way, here's an example which works great:
<?xml version="1.0" encoding="utf-8"?>
<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">
<fx:Script>
<![CDATA[
[Bindable] private var someText:String = "Enter long text here.";
]]>
</fx:Script>
<s:RichEditableText selectable="true" editable="false" text="{someText}" multiline="true" width="100%" />
</s:Application>

Multiple downloads in flex

can someone help me?
I want to download files from the server side to client side without prompting a window to the user to download when any updates happen at server side.
Right now I am using urlstream class but first file is downloading completely rest of the files contents downloading partially.
edit
Code sample taken from other post. Warning: it's a huuuge chunk o'code.
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComp="client.components.*" layout="absolute" height="554" width="817"
backgroundGradientAlphas="[1.0, 0.0]"
backgroundGradientColors="[#ABA9A7, #03143B]" creationComplete="init();">
<mx:Script>
<![CDATA[
import flash.system.Capabilities;
import mx.collections.XMLListCollection;
import mx.rpc.Fault;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.events.ListEvent;
import mx.collections.ArrayCollection;
import flash.data.SQLConnection;
import flash.errors.SQLError;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
import flash.errors.SQLError;
import mx.controls.Alert;
import mx.events.CloseEvent;
import flash.net.*;
import flash.filesystem.*;
import flash.events.OutputProgressEvent;
private var urlstring:String="server path";
private var urlReq:URLRequest;
private var urlStream:URLStream;
private var fileData:ByteArray = new ByteArray();
private var sqlConnection:SQLConnection =null;
private var sql:String;
private var result:SQLResult;
private var stmt:SQLStatement=null;
private var catid:int=0;
private var testcollection:Array=new Array();
[Bindable]
private var DGArray:ArrayCollection = new ArrayCollection(testcollection);
private var number:int;
private var selection:Boolean=false;
private var timestamp:String;
private var xmlcol:XMLListCollection;
private var categoryid:int=0;
private var numbers:int;
private var index:int=0;
private var findex:int=0;
private var nupdates:int=0;
private var newfile:String="";
private var selectstream:int=1;
private var startdownload:Boolean=false;
public function init():void{
userRequest.send(null);
sqlConnection= new SQLConnection();
//create a new db-file in the application storage location
var file:File = new File("app:/E-catalog.db");
sqlConnection.addEventListener(SQLEvent.OPEN,dbOpenedHandler);
sqlConnection.addEventListener(SQLErrorEvent.ERROR,dbErrorHandler);
sqlConnection.open(file);
getData();
}
public function loaded(event:Event):void {
urlStream.readBytes(fileData, 0, urlStream.bytesAvailable);
for(var x:int=0;x<nupdates;x++){
var filename:Object=xmlcollection.getItemAt(x);
newfile=filename['pdfimage'];
writeAirFile();
}
}
public function writeAirFile():void {
/*
var obj:Object=new Object;
startdownload=true;
var file:File = File.applicationStorageDirectory.resolvePath(newfile);
fileStream = new FileStream();
fileStream.openAsync(file, FileMode.WRITE);
fileStream.writeBytes(fileData, 0, fileData.length);
fileStream.addEventListener(Event.COMPLETE,progressHandler,true,10,true);
for(var x:int=0;x<fileData.length;x++){}
startdownload=false;
fileStream.close();
*/
}
public function progressHandler(event:Event){
Alert.show("File downloading");
}
public function dbOpenedHandler(event:SQLEvent):void{}
public function dbErrorHandler(error:SQLError):void{}
public function getData():void{
sql = "SELECT STRFTIME('%Y-%m-%d %H:%M:%S',lupdated_dt)as lupdated_dt FROM update_mas where delflag=0 ";
stmt = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.addEventListener(SQLEvent.RESULT, selectResult);
stmt.addEventListener(SQLErrorEvent.ERROR, selectError);
stmt.execute();
}
public function selectResult(event:SQLEvent){
DGArray.removeAll();
number=1;
var result = stmt.getResult();
var numRows = result.data.length;
for (var i = 0; i < numRows; i++){
for(var col:String in result.data[i]){
timestamp=result.data[i][col];
}
}
updateRequest.url="serverpath ?time="+timestamp+"";
updateRequest.send(null);
}
public function selectError(event):void{
stmt.removeEventListener(SQLEvent.RESULT, selectResult);
stmt.removeEventListener(SQLErrorEvent.ERROR, selectError);
Alert.show("SELECT error:");
}
public function displayPOPUP(event:ResultEvent):void{
nupdates=((int)(event.result));
if(nupdates==0){
}else{
selection=Alert.show(""+nupdates+"Updates available", "UPDATES", Alert.YES|Alert.NO, this, alertClickHandler);
}
}
private function alertClickHandler(event:CloseEvent):void {
if (event.detail==Alert.YES){
downloadRequest.url="serverpath ?time="+timestamp;
downloadRequest.send(null);
}else
Alert.show("download cancelled");
}
public function displayResult(event:ResultEvent):void{
var record:String="";
sql="";
for(index=0;index<xmlcollection.length;index++){
var category:Object=xmlcollection.getItemAt(index);
sql="select Id FROM CATEGORY where delflag=0 and cat_name='"+category['catname']+"'";
stmt = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.addEventListener(SQLEvent.RESULT,checkRecord);
stmt.addEventListener(SQLErrorEvent.ERROR,checkError);
stmt.execute();
}
}
public function checkRecord(event:Event):void{
var category:Object=xmlcollection.getItemAt(index);
var path:String="";
var result:SQLResult = stmt.getResult();
if(result.data==null){
var sql:String= "INSERT INTO CATEGORY (cat_name, created_user,created_dt,updated_user,updated_dt,image_jpg,image_pdf) ";
sql += "VALUES ('"+category['catname']+"',";
sql +="'admin','"+category['cdate']+"','admin','"+category['udate']+"'"+category['pictimage']+"','"+category['pdfimage']+"' )";
stmt = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.addEventListener(SQLEvent.RESULT,insertRecord);
stmt.addEventListener(SQLErrorEvent.ERROR,insertError);
stmt.execute();
}else{
sql="";
sql="update CATEGORY set created_dt='"+category['cdate']+"', updated_dt='"+ category['udate']+"',image_jpg='"+category['pictimage']+"', image_pdf='"+category['pdfimage']+"' where delflag=0 and cat_name='"+category['catname']+"'";
stmt = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.addEventListener(SQLEvent.RESULT,updateResult);
stmt.addEventListener(SQLErrorEvent.ERROR,updateError);
stmt.execute();
}
userRequest.send(null);
var ludt_dt:Object=xmlcollection.getItemAt((xmlcollection.length-1));
timestamp="";
timestamp=ludt_dt['udate'];
sql="";
sql="update update_mas set lupdated_dt='"+timestamp+"' where delflag=0 ";
stmt = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.addEventListener(SQLEvent.RESULT,updateResult);
stmt.addEventListener(SQLErrorEvent.ERROR,updateError);
stmt.execute();
var temp:int=0;
for(var x:int=0;x<=xmlcollection.length-1;){
var urlstring:String="http://sidssoldc:81/lessons/ravi/";
var url:Object=xmlcollection.getItemAt(x);
urlstring+=url['pdfimage'];
path=url['pdfimage'];
while((path.indexOf('/',0)!=-1)){
path=path.slice(path.indexOf('/',0)+1,path.length);
}
urlReq=new URLRequest(urlstring);
var filename:Object=xmlcollection.getItemAt(x);
var loader:URLLoader=new URLLoader();
loader.dataFormat="binary";
selectstream=2;
loader.load(urlReq);
loader.addEventListener(Event.COMPLETE,function(event:Event){
var loader:URLLoader=(URLLoader)(event.target);
loader.dataFormat="binary";
var ofstream2:FileStream= new FileStream();
var ofstream1:FileStream= new FileStream();
var ofstream3:FileStream= new FileStream();
if(selectstream==1){
var ofile1:File = File.applicationStorageDirectory.resolvePath('images/pdf/'+path);
ofstream1.openAsync(ofile1, FileMode.WRITE);
ofstream1.writeBytes(loader.data, 0, loader.bytesTotal);
selectstream++;
}else if(selectstream==2){
ofstream1.close();
var ofile2:File = File.applicationStorageDirectory.resolvePath('images/pdf/'+path);
ofstream2.openAsync(ofile2, FileMode.WRITE);
ofstream2.writeBytes(loader.data, 0, loader.bytesTotal);
selectstream++;
}else if(selectstream==3){
ofstream2.close();
var ofile3:File = File.applicationStorageDirectory.resolvePath('images/pdf/'+path);
ofstream3.openAsync(ofile3, FileMode.WRITE);
ofstream3.writeBytes(loader.data, 0, loader.bytesTotal);
}
if(selectstream==3){
ofstream3.close();
}
});
x++;
temp=loader.bytesTotal;
checkStream.close();
}
/*urlStream=new URLStream();
urlStream.addEventListener(Event.COMPLETE, function(event:Event){
urlStream.readBytes(fileData, 0, urlStream.bytesAvailable);
for(var x:int=0;x<nupdates;x++){
var filename:Object=xmlcollection.getItemAt(x);
newfile=filename['pdfimage'];
var obj:Object=new Object;
startdownload=true;
var file:File = File.applicationStorageDirectory.resolvePath(newfile);
var fileStream:FileStream = new FileStream();
fileStream.openAsync(file, FileMode.WRITE);
fileStream.writeBytes(fileData, 0, fileData.length);
fileStream.addEventListener(Event.COMPLETE,progressHandler,true,10,true);
for(var x:int=0;x<fileData.length;x++){
startdownload=false;
fileStream.close();
}
});
urlStream.load(urlReq);
x++;*/
}
public function insertRecord(event:Event):void{}
public function insertError(event:Event):void{}
public function updateResult(event:Event):void{}
public function updateError(event:Event):void{
Alert.show("update failed");
}
public function checkError(event:Event):void{
Alert.show("error");
}
public function showError(event:FaultEvent):void{
Alert.show(""+event.fault);
}
public function itemClick(event:ListEvent):void{}
]]>
</mx:Script>
<mx:DataGrid id="dgUserRequest" sortableColumns="false" x="99" y="115" width="364" textAlign="left" itemClick="itemClick(event);" rowHeight="30" doubleClickEnabled="false" height="297" themeColor="#ACF4F8" visible="true" editable="false" dataProvider="{catxmlcollection}" color="#000C0E" fontSize="11" >
<mx:columns>
<mx:DataGridColumn id="ID" headerText="Id" visible="false" dataField="catid" />
<mx:DataGridColumn id="snumber" width="70" headerText="SerialNo" dataField="sno" visible="true" />
<mx:DataGridColumn id="CATEGORY3" width="250" headerText="CATEGORY" dataField="catname" visible="true" />
</mx:columns>
</mx:DataGrid>
<mx:XMLListCollection id="catxmlcollection" source="{userRequest.lastResult.categories.category}"/>
<mx:HTTPService id="userRequest" url="http://192.168.10:81/lessons/ravi/cat.php" fault="showError(event);" useProxy="false" method="GET" resultFormat="e4x" />
<mx:HTTPService id="updateRequest" result="displayPOPUP(event);" fault="showError(event);" method="GET" > </mx:HTTPService>
<mx:XMLListCollection id="xmlcollection" source="{downloadRequest.lastResult.Categories.Category}" />
<mx:HTTPService id="downloadRequest" result="displayResult(event);" fault="showError(event);" useProxy="false" method="GET" resultFormat="e4x" ></mx:HTTPService>
<mx:HTTPService id="categoryRequest"></mx:HTTPService>
<mx:Label x="216" y="53" text="Category Master" fontWeight="bold" fontSize="12" width="151"/>
</mx:WindowedApplication>
You need to provide more details. I can't even understand whether you want to refresh data from the server or want to download files without the user's permission. If it's the former, polling is the way to go. For the latter, you might as well shut shop because nobody's going to use an app that downloads stuff without asking first.
.p
I have had some issues when sending multiple requests simultaneously... when, for example, trying to load twenty images at the same time only some of them were received properly. I am not sure what was causing this, but I would suggest you try doing the transfers in a sequence since it solved all of my problems. In practice you might put them in an array and always take and remove the top one when the previous one completes.

How to generate a form(<mx:form>) dynamically in flex?

I need to generate a mx:form from an xml file that I am getting from httpservice.
Also I need to prefill the data that I am getting from the form itself.
Can someone give me a sample code?
You would have to expand on this obviously, but this is how I would go about building a dynamic form..
import mx.controls.TextInput;
import mx.containers.FormItem;
import mx.containers.Form;
private var fxml:XML =
<form>
<fields>
<field type="text" label="name" default="gary"/>
<field type="text" label="surname" default="benade"/>
</fields>
</form>
private function init():void
{
var form:Form = new Form();
form.setStyle("backgroundColor", 0xFFFFFF);
for each( var xml:XML in fxml..field)
{
switch( xml.#type.toString())
{
case "text":
var fi:FormItem = new FormItem();
fi.label = xml.#label;
var ti:TextInput = new TextInput();
ti.text = xml.#default.toString();
fi.addChild( ti);
form.addChild( fi);
break;
case "int":
break;
}
}
this.addChild( form);
}
Check this out: MXMLLoader for Flex 3. HTH.
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="handleCreationComplete()">
<fx:Declarations>
<fx:XML id="formdata">
<userinfoform>
<user>
<firstname inputtype="TextInput" formlabel="First Name" required="true">true</firstname>
<lastname inputtype="TextInput" formlabel="Last Name" required="true">true</lastname>
<Middlename inputtype="TextInput" formlabel="Middle Name" required="false">true</Middlename>
<nickname inputtype="TextInput" formlabel="Nick Name" required="false">false</nickname>
<combobox inputtype="ComboBox" formlabel="Gender" required="true">Male,Female</combobox>
<type inputtype="ComboBox" formlabel="Type" required="false">Book,Cds,Games</type>
<radioButtonGroup inputtype="RadioButtonGroup" formlabel="Gender" required="false">
<radiobutton inputtype="RadioButton" formlabel="Gender" required="true">Male</radiobutton>
<radiobutton inputtype="RadioButton" formlabel="Gender" required="true">Female</radiobutton>
</radioButtonGroup>
</user>
</userinfoform>
</fx:XML>
</fx:Declarations>
`enter code here`<fx:Script>
<![CDATA[
import flashx.textLayout.events.SelectionEvent;
import mx.collections.ArrayCollection;
import mx.core.UIComponent;
import mx.events.ItemClickEvent;
import mx.events.ValidationResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.validators.NumberValidator;
import mx.validators.StringValidator;
import spark.components.ComboBox;
import spark.components.DropDownList;
import spark.components.RadioButton;
import spark.components.RadioButtonGroup;
import spark.components.TextArea;
import spark.components.Form;
import spark.components.FormItem;
import spark.components.TextInput;
import spark.components.RadioButtonGroup;
import spark.components.RadioButton;
private function handleCreationComplete():void
{
//Below line can be used for XML from an external source
//XMLService.send();
buildForm(new XML(formdata));
}
private function errorHandler(evt:FaultEvent):void
{
//Alert.show("Error: " + evt.fault.message);
}
private function resultHandler(evt:ResultEvent):void
{
buildForm(new XML(evt.result));
}
private function buildForm(xml:XML):void
{
var lst:XMLList = xml.children();
for(var i:int = 0; i < lst.length(); i++)
{
var x:XMLList = lst[i].children();
for(var j:int = 0; j < x.length(); j++)
{
if(x[j].#inputtype == 'TextInput')
{
var frmItem:FormItem = new FormItem();
//frmItem.direction = "horizontal";
frmItem.label = x[j].#formlabel;
// make sure boolean is pasrsed to a string before assigned
// to required property of the formitem
var validString : String = x[j].#required;
var valid : Boolean = (validString == "true");
frmItem.required = valid;
var tb:TextInput = new TextInput();
tb.text = x[j];
frmItem.addElement(tb);
userInfoForm.addElement(frmItem);
}
else if(x[j].#inputtype == 'ComboBox')
{
var frmItemCB:FormItem = new FormItem();
//frmItemCB.direction = "horizontal";
frmItemCB.label = x[j].#formlabel;
// make sure boolean is pasrsed to a string before assigned
// to required property of the formitem
var validString : String = x[j].#required;
var valid : Boolean = (validString == "true");
frmItemCB.required = valid;
// make sure the string is split, assigned to an array, and parsed
// to an arraycollection to assgn it as dataprovider for dropdownlist
var str:String = x[j];
var arr:Array = str.split(",");
var arrcol:ArrayCollection = new ArrayCollection();
for(var k:int = 0; k < arr.length; k++)
{
var obj:Object = {name:arr[k]}
arrcol.addItem(obj);
}
var cb:DropDownList = new DropDownList();
cb.dataProvider = arrcol;
cb.labelField = "name";
frmItemCB.addElement(cb);
userInfoForm.addElement(frmItemCB);
}
else if(x[j].#inputtype == 'RadioButtonGroup')
{
var frmItemRB:FormItem = new FormItem();
//frmItemRB.direction = "horizontal";
frmItemRB.label = x[j].#formlabel;
// make sure boolean is pasrsed to a string before assigned
// to required property of the formitem
var validString : String = x[j].#required;
var valid : Boolean = (validString == "true");
frmItemRB.required = valid;
var frmItemRB1:FormItem = new FormItem();
frmItemRB1.addElement(label);
var y:XMLList = x[j].children();
var radioGroup = new RadioButtonGroup();
radioGroup.addEventListener(ItemClickEvent.ITEM_CLICK,
radioGroup_itemClick);
for(var l:int = 0; l < y.length(); l++)
{
var rb = new RadioButton();
rb.label = y[l];
rb.group = radioGroup;
frmItemRB.addElement(rb);
userInfoForm.addElement(frmItemRB);
}
}
}
}
}
public var label:TextInput = new TextInput();
private function radioGroup_itemClick(evt:ItemClickEvent):void {
label.text = evt.label ;
}
/**
* Helper function that returns all the fields for a
* given form. Pass in requiredOnly = true if you only want
* the required fields.
*/
private function getFields(form:Form, requiredOnly:Boolean=false):Array
{
var a:Array = [];
return a;
}
/**
* Validates all fields in a given form.
*/
private function validateForm(form:Form):Boolean
{
// reset the flag
var _isValid:Boolean = true;
var _notValid:Boolean = false;
// populate the fields - if your fields aren't dynamic put this in creationComplete
var fields:Array = getFields(form, true);
for each(var source:UIComponent in fields)
{
// create a simple string validator
var stringValidator:StringValidator = new StringValidator();
stringValidator.minLength = 2;
stringValidator.source = source;
stringValidator.property = "text";
stringValidator.requiredFieldError = "This field is required!!!";
var numberValidator:NumberValidator = new NumberValidator();
numberValidator.minValue = 0;
numberValidator.source = source;
numberValidator.property = "text";
numberValidator.lowerThanMinError = "This field is required!!!";
var rbValidator:StringValidator = new StringValidator();
rbValidator.minLength = 1;
rbValidator.maxLength = 80;
rbValidator.source = source;
rbValidator.property = "selectedValue";
rbValidator.requiredFieldError = "This field is required!!!";
var result:ValidationResultEvent;
//var radiogroup:spark.components.RadioButtonGroup = new spark.components.RadioButtonGroup;
// typical validation, but check to this checks for any different
// types of UIComponent here
if (source is TextInput)
result = stringValidator.validate(TextInput(source).text)
else if (source is TextArea)
result = stringValidator.validate(TextArea(source).text)
else if (source is DropDownList)
result = numberValidator.validate(DropDownList(source).selectedIndex)
//else if (source is Label)
//result = stringValidator.validate(Label(source).text)
//if(source is spark.components.RadioButton)
//result = numberValidator.validate(mx.controls.RadioButton(source))
// if the source is valid, then mark the form as valid
_isValid = (result.type == ValidationResultEvent.VALID) && _isValid;
}
return _isValid;
}
protected function submitButton_clickHandler(event:MouseEvent):void
{
if(validateForm(userInfoForm) == true)
{
//Alert.show("Proceed Genius!!!","Alert");
}
else
{
//Alert.show("Open ur eyes and fill the form properly u morron!!!","Morron");
}
}
]]>
</fx:Script>
<fx:Declarations>
<!--Below line can be used for XML from an external source-->
<!--<mx:HTTPService fault="errorHandler(event)" id="XMLService" resultFormat="e4x" url="formdata.xml" result="resultHandler(event)" />-->
</fx:Declarations>
<s:VGroup width="100%">
<s:Form id="userInfoForm" />
<s:Button label="Submit" id="submitButton" click="submitButton_clickHandler(event)"/>
</s:VGroup>
</s:View>

Resources