actionscript to populate a list from sqlite table - sqlite

using Adobe Flash Builder 4.6
the below code is what I am using to try to get actionscript to populate a list a from sqlite table. It brings back the correct number of records but it shows the results as:
[object Object]
[object Object]
[object Object]
Can someone tell me what I may be doing wrong?
private var strGetDBName:String = "CPRInstr.db";
private var strGetCurrentTableName:String = "lkStates";
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.filesystem.File;
import mx.collections.ArrayCollection;
private var conn:SQLConnection;
private function init():void
{
conn = new SQLConnection();
conn.addEventListener(SQLEvent.OPEN, openSuccess);
//conn.addEventListener(SQLErrorEvent.ERROR, openFailure);
var dbFile:File = File.applicationDirectory.resolvePath(strGetDBName);
conn.openAsync(dbFile);
}
private function openSuccess(event:SQLEvent):void
{
conn.removeEventListener(SQLEvent.OPEN, openSuccess);
//conn.removeEventListener(SQLErrorEvent.ERROR, openFailure);
getData();
}
private function getData():void
{
var select:SQLStatement = new SQLStatement();
select.sqlConnection = conn;
//select.text = "SELECT id, txtState, txtAbbrev FROM " + strGetCurrentTableName;
select.text = "SELECT id, txtState FROM lkStates";
select.addEventListener(SQLEvent.RESULT, selectResult);
//select.addEventListener(SQLErrorEvent.ERROR, selectError);
select.execute();
}
private function selectResult(event:SQLEvent):void
{
var result:SQLResult = null;
result = event.currentTarget.getResult();
if(result.data)
{
list.dataProvider = new ArrayCollection(result.data);
}
}

This worked for me, I tried to match your variables for example.
var result:SQLResult = select.getResult();
list.dataProvider = new DataProvider(result.data);
if(result.data)
{
for(var i:int = 0; i < result.data.length; i++)
{
var tState:Object = result.data[i];
trace("var1 "+tState.var1+"var2 "+tState.var2...etc)
}
}

You need to set labelField to your list to a field name in your table so that it can appear in the list. In the declaration of your list type : labelField = "txtState" and you will get the information from this field.

Related

Passing Variables to ASPX to the URL String from AS3 - Message Failed

Im trying to send three variables (fname, lname, and email) to append them to the URL string like this http://www.whatever.com?address=&firstname=&lastname=&email= and it traced as "Message Failed" I wonder what I did wrong with this code.
in Flash 'fname_txt', 'lname_txt', and 'email_txt' are the instance names of the Input Text
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.net.navigateToURL;
mcButton.addEventListener(MouseEvent.MOUSE_UP, onClick);
function onClick(e:MouseEvent):void {
var scriptRequest:URLRequest = new URLRequest("../index.aspx");
var scriptLoader:URLLoader = new URLLoader();
var scriptVars:URLVariables = new URLVariables();
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
scriptVars.fname = fname_txt.text;
scriptVars.lname = lname_txt.text;
scriptVars.email = email_txt.text;
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
function handleLoadSuccessful($evt:Event):void
{
trace("Message sent.");
}
function handleLoadError($evt:IOErrorEvent):void
{
trace($evt); <----------------UPDATED
}
fname_txt.text = "";
lname_txt.text = "";
email_txt.text = "";
}

How can I take a screen shot of entire Screen on regular intervals using Adobe flex and action script

How can I take screen shot of Entire on Screen regular intervals (random between 2 to 5 minutes) without click event using Adobe flex and action script. Currently I am doing it with the Mouse_Up Event and then calling the timer and then saving each image with different name
package
{
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.events.MouseEvent;
import flash.events.NativeProcessExitEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.system.Capabilities;
import flash.utils.Timer;
public class Grabber extends Sprite
{
private var stageCover:Sprite;
private var captureRect:Sprite;
private var sx:Number;
private var sy:Number;
private var np:NativeProcess;
private var npi:NativeProcessStartupInfo;
public function Grabber()
{
super();
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stageCover = new Sprite();
stageCover.graphics.beginFill(0xFFFFFF, 0.01);
stageCover.graphics.drawRect(0, 0, Capabilities.screenResolutionX, Capabilities.screenResolutionY);
addChild(stageCover);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
captureRect = new Sprite();
captureRect.graphics.lineStyle(2, 0xFFFFFF);
addChild(captureRect);
np = new NativeProcess();
npi = new NativeProcessStartupInfo();
}
private function onTimerComplete( event:TimerEvent):void
{
captureRect.graphics.clear();
var args:Vector.<String> = new Vector.<String>();
args.push("-l");
sx =0;
args.push(sx.toString());
args.push("-t");
sy = 0 ;
args.push(sy.toString());
args.push("-r");
var a:Number = Capabilities.screenResolutionX;
args.push(a.toString());
args.push("-b");
var b:Number= Capabilities.screenResolutionY;
args.push(b.toString());
args.push("-out");
args.push(File.desktopDirectory.nativePath + "/grab.jpeg");
npi.arguments = args;
npi.executable = File.applicationDirectory.resolvePath("GrabberCommand.exe");
np.start(npi);
}
private function onMouseUp(event:MouseEvent):void
{
var timer:Timer=new Timer( 10*1000*Math.random(),1 );
timer.addEventListener( TimerEvent.TIMER, onTimerComplete );
timer.start();
}
}
}
XML Properties are
SystemChrome none
Transparent true
SupportedProfiles extendedDesktop
I actually did something like this before.
You will need a Timer that calls the following function at intervals (whatever intervals you like):
private function captureScreenshots(event:MouseEvent):void
{
var imgEnc:IImageEncoder;
var screenshotArray:Array = new Array();
if(myView.encodingCombo.selectedItem == "PNG")
{
imgEnc = pngEnc; //private const pngEnc:PNGEncoder = new PNGEncoder();
}
else
{
imgEnc = jpgEnc; //private const jpgEnc:JPEGEncoder = new JPEGEncoder();
}
var windowsArray:Array = NativeApplication.nativeApplication.openedWindows;
for each(var window:NativeWindow in windowsArray)
{
if(window && window.stage is IBitmapDrawable)
{
var imageSnapshot:ImageSnapshot = ImageSnapshot.captureImage(window.stage as IBitmapDrawable, 0, imgEnc);
screenshotArray.push(imageSnapshot);
}
}
windowsArray = null;
}
You can then use a FileStream to write them to a directory, but that would be a different question.

Flex:Not able to load Excel files from folder and update them (delete )

I am trying to delete a line from 50 excel files and for that I am making a tool in flex to go through a folder, find xls files and then perform operation on it.I am facing two issues here:
1. I have a loop which iterates on the folder and once a xls is found it should call a function to delete the line and come back to the for loop and continue with the other excel files in the folder. But it is not doing so.
2.I am not able to delete and row in excel .I am using as3xls to work with excel.In this I am setting a value to of the row which I don't require as blank as I don't know how to delete it.
I am new to flex so please help.
enter code here
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:mx="library://ns.adobe.com/flex/mx" layout="absolute"
creationComplete="onCreate(event)">
<fx:Script>
<![CDATA[
import com.as3xls.xls.Cell;
import com.as3xls.xls.ExcelFile;
import com.as3xls.xls.Sheet;
import flash.filesystem.FileMode;
import flash.utils.Timer;
// import flash.events.TimerEvents;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
private var sheet:Sheet;
private var interval: uint;
private var loadedFile:ByteArray;
function trigger():void { setTimeout(doIt, 10000); }
function doIt():void { }
private function onCreate(e:Event):void
{
var fileDirectry:File = File.documentsDirectory.resolvePath("D:/temp");
var excelFile:File = null;
var files:Array = fileDirectry.getDirectoryListing();
for(var i:int = 0; i < files.length; i++){
var temp:File = files[i];
if(temp.extension == "xls"){
excelFile = temp;
break;
//var request:URLRequest = new URLRequest(excelFile.nativePath);
//var urlLoader:URLLoader = new URLLoader(request);
//urlLoader.addEventListener(Event.COMPLETE, onURLLoaderComplete); // Once file loaded, function call onURLLoaderComplete
//urlLoader.dataFormat = URLLoaderDataFormat.BINARY; // to Read Data in Binary Format
//urlLoader.load(request);
//trigger();
// interval=setTimout( onCreate(event) ,200);
}
}
var request:URLRequest = new URLRequest(excelFile.nativePath);
var urlLoader:URLLoader = new URLLoader(request);
urlLoader.addEventListener(Event.COMPLETE, onURLLoaderComplete); // Once file loaded, function call onURLLoaderComplete
urlLoader.dataFormat = URLLoaderDataFormat.BINARY; // to Read Data in Binary Format
urlLoader.load(request);
}
private function onURLLoaderComplete(event:Event):void
{
loadedFile = event.target.data;
var excelFile:ExcelFile = new ExcelFile();
excelFile.loadFromByteArray(loadedFile);
sheet = excelFile.sheets[0]; // Reads sheet1
//trace(sheet.getCell(1,1).value);
//Alert.show(sheet.getCell(0,0).value)// getCell(Row, Col)
var rows:int = sheet.rows;
var cols:int = sheet.cols;
for(var i:int = 0; i < rows; i++){
for(var j:int = 0; j < cols; j++){
if(sheet.getCell(i,j).toString() == "second" || sheet.getCell(i,j).toString() == "Second" )
{
Alert.show(sheet.getCell(i,j-1).value)
for (var k:int =0;k< cols;k++){
sheet.setCell(i,k,'');
}
excelFile.sheets.addItem(sheet);
var ba:ByteArray = excelFile.saveToByteArray();
var fr:FileReference = new FileReference();
fr.save(ba,"SampleExport1.xls");
//sheet.
//TypeLib name and TypeDef Id
}
}
}
//Alert.show(sheet.getCell(0,0).value)
//return ;
//DG.dataProvider=sheet.values; // Imports all excel cells to Datagrid
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</mx:WindowedApplication>
The problem is that loading is an asynchronous operation, so you need to create some kind of system to pause the processing of the loop until the load is complete. Something like this should work:
public class ProcessFilesCommand
{
private var _files:Array;
private var _index:int = 0;
public function processFiles(path:String):void
{
_index = 0;
var fileDirectry:File = File.documentsDirectory.resolvePath(path);
_files = fileDirectry.getDirectoryListing();
if(!_files || _files.length == 0)
return; //or dispatch a complete event
processFileAt(0);
}
private function cleanFile(data:Object):void
{
//do your excel stuff here
}
private function processFileAt(index:int):void
{
trace("ProcessFilesCommand.processFileAt(" + index + ")");
if(index >= _files.length)
{
//maybe a good spot to dispatch a complete event...
return;
}
var file:File = File(_files[_index]);
if(file.isDirectory || file.extension == null || file.extension.toLowerCase() != "xls")
{
processFileAt(++_index);
}
else
{
var request:URLRequest = new URLRequest(file.nativePath);
var loader:URLLoader = new URLLoader(request);
loader.addEventListener(Event.COMPLETE, loader_completeHandler); // Once file loaded, function call onURLLoaderComplete
loader.dataFormat = URLLoaderDataFormat.BINARY; // to Read Data in Binary Format
loader.load(request);
}
}
private function loader_completeHandler(event:Event):void
{
trace("ProcessFilesCommand.loader_completeHandler(event)");
cleanFile(event.target.data);
processFileAt(++_index)
}
}

Flex Syntax Error

I am getting Syntax Error 1202 (Access of undefined property connection in package model) in the following code while trying to access the model.connection property. I don't see any reason why this would appear, can anyone see something I may be overlooking?
Model.as
package valueObjects
{
import flash.data.SQLConnection;
import mx.collections.ArrayCollection;
public class Model
{
public var connection:SQLConnection;
public var albums:ArrayCollection = new ArrayCollection();
public var albumItems:ArrayCollection = new ArrayCollection();
public var selectedAlbum:Number = 0;
public var selectedItem:Number = 0;
public function Model()
{
}
}
}
And the actual code in my default mxml file, init() is called on initialize
import model.ModelLocator;
import mx.core.mx_internal;
import valueObjects.Model;
protected var sqlConnection:SQLConnection;
private var model:Model = new Model();
protected function init():void
{
createDb();
navigator.firstViewData = model;
}
protected function createDb():void
{
sqlConnection = new SQLConnection();
sqlConnection.open(File.applicationStorageDirectory.resolvePath("Oxford.db"));
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text =
"CREATE TABLE IF NOT EXISTS albumItems (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"album INTEGER, " +
"name STRING, " +
"dateAdded DATE)";
stmt.execute();
model.connection = sqlConnection;
}
The issue here is that you have a package and a variable named 'model'. When you try to access the variable named model, it thinks you are referring to the package. If you correct this naming collision, you will see that this issue is fixed.

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