Connecting Flex to SQLite - apache-flex

In Flash builder, I'm struggling with basics of data retrieval from local database. Using Lita, I created a SQLite database with a single basic (item) table located in a "DAO" folder .It is meant to populate a List. and I have 2 problems:
How to embed the database (with all its pre-populated data) without recreating it from scratch as shown in many tutorials ?
For the purpose of prototyping, how to link the data retrieved a single MXML file directly in the list without creating many other classes (ok, in this cases the number of required classes would be limited) such as :
<?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"
title="HomeView" >
<fx:Script>
<![CDATA[
import flash.data.SQLConnection
import flash.data.SQLStatement;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import mx.collections.ArrayCollection;`
private function get myData():ArrayCollection
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = new SQLConnection();
stmt.sqlConnection.open(File.applicationStorageDirectory.resolvePath("dao/MyDatabase.db"));
stmt.text = "SELECT id, name FROM Item";
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
var list:ArrayCollection = new ArrayCollection();
list.source(result);
return list;
} else {
return null;
}
}
]]>
</fx:Script>
<s:List id="list" top="0" bottom="0" left="0" right="0"
dataProvider="{myData}" >
<s:itemRenderer>
<fx:Component>
<s:IconItemRenderer label="{myData.name}">
</s:IconItemRenderer>
</fx:Component>
</s:itemRenderer>
</s:List>
</s:View>

For the question 1 you can add the database as an asset of the project, during the export release it will be embeded into the installer then if you want to place it into the localstore folder you can copy/move it from code...
For the number 2
import flash.data.SQLConnection
import flash.data.SQLStatement;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import mx.collections.ArrayCollection;`
[Bindable]private var resultArr:ArrayCollection = new ArrayCollection();
private function getData():ArrayCollection
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = new SQLConnection();
stmt.sqlConnection.open(File.applicationStorageDirectory.resolvePath("dao/MyDatabase.db"));
stmt.text = "SELECT id, name FROM Item";
stmt.execute();
var result:Array = stmt.getResult().data;
resultArr = new ArrayCollection();
if (result)
{
resultArr.source = result;
}
}
]]>
</fx:Script>
<s:List id="list" top="0" bottom="0" left="0" right="0"
dataProvider="{resultArr}" labelField="name" >
</s:List>

Thanks to Marcx and Marcos Placona's Blog entry on copying database locally I came up with this:
<?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"
title="HomeView" >
<fx:Script>
<![CDATA[
import flash.data.SQLConnection
import flash.data.SQLStatement;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import mx.collections.ArrayCollection;
private function get myData():ArrayCollection
{
var myData:String = "dao/MyDatabase.db";
var embededSessionDB:File = File.applicationDirectory.resolvePath(myData);
var writeSessionDB:File = File.applicationStorageDirectory.resolvePath(myData);
// If a writable DB doesn't exist, we then copy it into the app folder so it's writteable
if (!writeSessionDB.exists)
{
embededSessionDB.copyTo(writeSessionDB);
}
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = new SQLConnection();
stmt.sqlConnection.open(File.applicationStorageDirectory.resolvePath(myData));
stmt.text = "SELECT id, name FROM Item";
stmt.execute();
var result:Array = stmt.getResult().data;
stmt.execute();
var result:Array = stmt.getResult().data;
var r:ArrayCollection = new ArrayCollection();
if (result)
{
r.source = result;
return r;
}else{
return null;
}
}
[Bindable]private var resultArr:ArrayCollection = getData();
]]>
</fx:Script>
<s:List id="list" top="0" bottom="0" left="0" right="0"
dataProvider="{myData}" label="name">
</s:List>
</s:View>

Related

Populating combobox with data from a datagrid, receiving data from a sqlite database

I'm still a newbie to Adobe Air/Flex, and still fairly new with SQL.
I've downloaded this (http://coenraets.org/blog/2008/11/using-the-sqlite-database-access-api-in-air…-part-1/) code and have been looking over it and I'm trying to implement a different idea.
I'm using a canvas for this form.
MaterialForm.mxml is called by a panel CadastroMaterial.mxml which also show a datagrid with the information saved from this form.
the sql statements are made by MaterialEvent.as using the lib flexlib.
I'm having a problem getting data from a datagrid to a combobox, I'm doing this way to get the data:
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" width="388" height="475" creationComplete="init()" label="{_material.material_id > 0 ? _material.tipo : 'Novo Material'}">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.managers.PopUpManager;
import Eventos.MaterialEvent;
import Eventos.TMaterialEvent;
import Formularios.TMaterialForm;
import mx.collections.ArrayCollection;
[Bindable] private var tMateriais:ArrayCollection;
// Para criar a conexão com o banco de dados
private function openDatabase():void
{
var file:File = File.applicationDirectory.resolvePath("bd/SISC.db");
sqlConnection = new SQLConnection();
sqlConnection.open(file);
// Para verificar se o banco de dados já existe se sim utiliza-o senão cria um novo, não é útil se não cria a tabela
//var isNewDB:Boolean = !file.exists;
//if (isNewDB) createDatabase();
findAll();
}
// Para selecionar a tabela do banco de dados desejada
private function findAll():void
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = "SELECT tmaterial FROM TMATERIAL";
stmt.execute();
tMateriais = new ArrayCollection(stmt.getResult().data);
}
[Bindable] public var _material:Object;
public var sqlConnection:SQLConnection;
private var validators:Array;
private function init():void
{
validators = [tipoValidator, responsavelValidator, compartimentoValidator];
openDatabase();// colocado para abrir o banco de outro lugar
}
public function set material(material:Object):void
{
_material = material;
}
public function get material():Object
{
return _material;
}
private function save():void
{
if (Validator.validateAll(validators).length>0)
{
return;
}
_material.tipo = tipo.text;
_material.num = num.text;
_material.responsavel = responsavel.text;
_material.compartimento = compartimento.text;
_material.observacoes = observacoes.text;
if (_material.material_id > 0)
{
update();
}
else
{
insert();
}
}
private function insert():void
{
try
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text =
"INSERT INTO material (tipo, num, responsavel, compartimento, observacoes) " +
"VALUES (:tipo, :num, :responsavel, :compartimento, :observacoes)";
stmt.parameters[":tipo"] = _material.tipo;
stmt.parameters[":num"] = _material.num;
stmt.parameters[":responsavel"] = _material.responsavel;
stmt.parameters[":compartimento"] = _material.compartimento;
stmt.parameters[":observacoes"] = _material.observacoes;
stmt.execute();
_material.material_id = stmt.getResult().lastInsertRowID;
label = _material.tipo;
dispatchEvent(new MaterialEvent(MaterialEvent.CREATE, _material, true));
}
catch (error:SQLError)
{
Alert.show(error.details, "Erro");
}
}
private function update():void
{
try
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text =
"UPDATE material set " +
"tipo=:tipo, " +
"num=:num, " +
"responsavel=:responsavel, " +
"compartimento=:compartimento, " +
"observacoes=:observacoes " +
"WHERE material_id=:materialId";
stmt.parameters[":tipo"] = _material.tipo;
stmt.parameters[":num"] = _material.num;
stmt.parameters[":responsavel"] = _material.responsavel;
stmt.parameters[":compartimento"] = _material.compartimento;
stmt.parameters[":observacoes"] = _material.observacoes;
stmt.parameters[":materialId"] = _material.material_id;
stmt.execute();
label = _material.tipo;
dispatchEvent(new MaterialEvent(MaterialEvent.UPDATE, _material, true));
}
catch (error:SQLError)
{
Alert.show(error.details, "Error");
}
}
private function deleteItem():void
{
try
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = "DELETE FROM material WHERE material_id = :materialId";
stmt.parameters[":materialId"] = _material.material_id;
stmt.execute();
dispatchEvent(new MaterialEvent(MaterialEvent.DELETE, _material, true));
}
catch (error:SQLError)
{
Alert.show(error.details, "Erro");
}
}
]]>
</mx:Script>
<mx:Validator id="tipoValidator" required="true" source="{tipo}" property="text"/>
<mx:Validator id="responsavelValidator" required="true" source="{responsavel}" property="text"/>
<mx:Validator id="compartimentoValidator" required="true" source="{compartimento}" property="text"/>
<mx:Form width="381" height="466">
<mx:FormItem label="Tipo:" required="true">
<mx:ComboBox dataProvider="{tMateriais}" id="tipo" text="{_material.tipo}" width="200"/>
</mx:FormItem>
<mx:FormItem label="Número:">
<mx:TextInput id="num" text="{_material.num}" width="200"/>
</mx:FormItem>
<mx:FormItem label="Responsavel:" required="true">
<mx:TextInput id="responsavel" text="{_material.responsavel}" width="200"/>
</mx:FormItem>
<mx:FormItem label="Compartimento:" required="true">
<mx:TextInput id="compartimento" text="{_material.compartimento}" width="200"/>
</mx:FormItem>
<mx:FormItem label="Observações:">
<mx:TextInput id="observacoes" text="{_material.observacoes}" width="200"/>
</mx:FormItem>
</mx:Form>
<mx:Button label="Salvar" click="save()" left="16" bottom="20"/>
<mx:Button label="Deletar" click="deleteItem()" left="87" bottom="20"/>
but as a result appears in the combobox [object Object] and not the name of the type of material inserted in the table TMATERIAL, if I insert 30 values ​​in Table tmaterial in another form, the 30 appear in combobox as [object Object] I traced this and the error are in this form. Could anyone help me? Sorry the english (google translator). Thnx.
The problem is the ComboBox needs a hint as to how it should show the name for each item in the dataProvider. By default, many Flex components look for the elements in the dataProvider to have a property named label. If such a property exists, and it is a String, the ComboBox will display the value of that label property.
If the elements in the dataProvider don't have a label property, then the Flex component will call toString() on the dataProvider object which in this case results in the output "[object Object]".
If the elements in your dataProvider do not have a label property, then you can tell the ComboBox how to display the name by using either the labelField or labelFunction properties of the ComboBox.
Use the labelField property to specify the name of the property in your dataProvider that can be used as the label (in your case I believe this is tipo or :tipo)
<mx:ComboBox dataProvider="{tMateriais}" id="tipo" labelField="tipo" />
Or use the labelFunction property specify a function that will be used to generate the label for each item in the dataProvider.
<mx:ComboBox dataProvider="{tMateriais}" id="tipo" labelFunction="myLabelFunction" />
The labelFunction has the following method signature:
private function myLabelFunction(dataProviderItem : Object) : String

SQLError #3115 Mismatch in parameter count

I am getting this error when I am trying to use the SQL UPDATE with a mobile application I am making in Flex builder. I have tried to search it up and removed parameters but even then I get the same code. Any help would be much appreciated
SQLError: 'Error #3115: SQL Error.', details:'Mismatch in parameter count. Found 6 in SQL specified and 5 value(s) set in parameters property.
', operation:'execute', detailID:'1004'
at flash.data::SQLStatement/internalExecute()
at flash.data::SQLStatement/execute()
at model::SQLiteDatabase$/updateMember()[/Users/stokhofdavey/Documents/Adobe Flash Builder 4.6/MenuPlannerApplication/src/model/SQLiteDatabase.as:175]
at views::MemberDetailsView/onSaveButtonClicked()[/Users/stokhofdavey/Documents/Adobe Flash Builder 4.6/MenuPlannerApplication/src/views/MemberDetailsView.mxml:25]
at views::MemberDetailsView/___MemberDetailsView_Button3_click()[/Users/stokhofdavey/Documents/Adobe Flash Builder 4.6/MenuPlannerApplication/src/views/MemberDetailsView.mxml:45]
Here is the MXML code:
<?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:ns1="*"
title="Member Details">
<fx:Script>
<![CDATA[
import model.Dish;
import model.Member;
import model.SQLiteDatabase;
protected function onHomeButtonClicked(event:MouseEvent):void {
navigator.popView();
}
protected function onSaveButtonClicked():void {
var editNote:Member = new Member();
editNote.FirstName = efirstname.text;
editNote.FamilyName = efamilyname.text;
editNote.Sex = esex.text;
editNote.Age = eage.text;
editNote.Notes = enotes.text;
SQLiteDatabase.updateMember(editNote);
currentState = "Info";
}
]]>
</fx:Script>
<s:states>
<s:State name="Info"/>
<s:State name="Favorites"/>
<s:State name="EInfo"/>
<s:State name="EFavorites"/>
</s:states>
<s:navigationContent>
<s:Button label="Back" click="navigator.popView();"/>
</s:navigationContent>
<s:actionContent>
<s:Button includeIn="Info" label="Edit" click.Info="this.currentState="EInfo""/>
<s:Button includeIn="EInfo" label="Save" click="onSaveButtonClicked()"/>
</s:actionContent>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:VGroup x="245" y="10" width="100%" height="354" gap="0" >
<ns1:TabMemInfoS includeIn="Favorites" width="60" height="40"/>
<ns1:TabMebInfoL includeIn="Info" width="70" height="40"/>
<ns1:TabMemFavoritesS includeIn="Info" width="60" height="40"/>
<ns1:TabMebInfoL includeIn="EInfo" width="70" height="40"/>
<ns1:TabMemFavoritesS includeIn="EInfo" width="60" height="40"/>
<ns1:TabMemInfoS includeIn="EFavorites"/>
<ns1:TabMemFavoritesL includeIn="EFavorites"/>
<ns1:TabMemFavoritesL includeIn="Favorites" width="70" height="40"/>
</s:VGroup>
<s:Label id="FirstName" includeIn="Info" x="87" y="15" width="148" height="29" text="{data.FirstName}" textAlign="center"
verticalAlign="middle"/>
<s:Label id="FamilyName" includeIn="Info" x="87" y="46" width="148" height="29" text="{data.FamilyName}" textAlign="center"
verticalAlign="middle"/>
<s:Label id="Age" includeIn="Info" x="9" y="97" width="70" height="31" text="{data.Age}" textAlign="center"
verticalAlign="middle"/>
<s:Label id="Sex" includeIn="Info" x="87" y="97" width="70" height="31" text="{data.Sex}" textAlign="center"
verticalAlign="middle"/>
<s:Label id="notes" includeIn="Info" x="10" y="150" width="225" height="204" text="{data.Notes}"/>
<s:Group includeIn="EInfo" width="246" height="364">
<s:TextInput id="efirstname" x="83" y="10" width="150" text="{data.FirstName}" />
<s:TextInput id="efamilyname" x="83" y="47" width="150" text="{data.FamilyName}" />
<s:TextInput id="eage" x="108" y="88" width="90" text="{data.Age}" />
<s:TextInput id="esex" x="10" y="88" width="90" text="{data.Sex}" />
<s:TextArea id="enotes" x="9" y="162" width="227" height="192" text="{data.Notes}" />
</s:Group>
</s:View>
and the 2 .as files:
SQLiteDatabase
package model
{
import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.events.SQLEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import model.Dish;
import model.Member;
import mx.collections.ArrayCollection;
public class SQLiteDatabase
{
private static var _sqlConnection:SQLConnection;
public static function get sqlConnection():SQLConnection
{
if (_sqlConnection)
return _sqlConnection;
openDatabase(File.desktopDirectory.resolvePath("test.db"));
return _sqlConnection;
}
public static function getNote(id:int):Dish
{
var sql:String = "SELECT id, title, time, message FROM notes WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = id;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result && result.length == 1)
return processRow(result[0]);
else
return null;
}
public static function getMYBlist(id:int):Dish
{
var sql:String = "SELECT id, title, time, message FROM notes WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = id;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result && result.length == 1)
return processRow(result[0]);
else
return null;
}
public static function notes():ArrayCollection
{
var noteList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, title, time, message FROM notes";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var sqlResult:SQLResult = stmt.getResult();
if (sqlResult) {
var result:Array = sqlResult.data;
if (result) {
for (var index:Number = 0; index < result.length; index++) {
noteList.addItem(processRow(result[index]));
}
}
}
return noteList;
}
public static function members():ArrayCollection
{
var noteList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT FirstName, FamilyName, Sex, Age, Notes FROM Members";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var sqlResult:SQLResult = stmt.getResult();
if (sqlResult) {
var result:Array = sqlResult.data;
if (result) {
for (var index:Number = 0; index < result.length; index++) {
noteList.addItem(processRow2(result[index]));
}
}
}
return noteList;
}
public static function addNote(note:Dish):void
{
var sql:String =
"INSERT INTO notes (title, time, message) " +
"VALUES (?,?,?)";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.title;
stmt.parameters[1] = note.time;
stmt.parameters[2] = note.message;
stmt.execute();
}
public static function addMember(note:Member):void
{
var sql:String =
"INSERT INTO notes (FirstName, FamilyName, Age, Sex, Notes) " +
"VALUES (?,?,?,?,?)";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.FirstName;
stmt.parameters[1] = note.FamilyName;
stmt.parameters[2] = note.Age;
stmt.parameters[3] = note.Sex;
stmt.parameters[4] = note.Notes;
stmt.execute();
}
public static function deleteNote(note:Dish):void
{
var sql:String = "DELETE FROM notes WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.id;
stmt.execute();
}
public static function deleteMember(note:Dish):void
{
var sql:String = "DELETE FROM notes WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.id;
stmt.execute();
}
public static function updateNote(note:Dish):void
{
var sql:String = "UPDATE notes SET title=?, time=?, message=? WHERE id=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.title;
stmt.parameters[1] = note.time;
stmt.parameters[2] = note.message;
stmt.parameters[3] = note.id;
stmt.execute();
}
public static function updateMember(note:Member):void
{
var sql:String = "UPDATE Members SET FirstName=?, FamilyName=?, Sex=?, Age=?, Notes=? WHERE ID=?";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = note.FirstName;
stmt.parameters[1] = note.FamilyName;
stmt.parameters[2] = note.Sex;
stmt.parameters[3] = note.Age;
stmt.parameters[4] = note.Notes;
stmt.execute();
}
protected static function processRow(o:Object):Dish
{
var note:Dish = new Dish();
note.id = o.id;
note.title = o.title == null ? "" : o.title;
note.time = o.time == null ? "" :o.time;
note.message = o.message == null ? "" : o.message;
return note;
}
protected static function processRow2(o:Object):Member
{
var info:Member = new Member();
info.ID = o.ID;
info.FirstName = o.FirstName == null ? "" : o.FirstName;
info.FamilyName = o.FamilyName == null ? "" : o.FamilyName;
info.Sex = o.Sex == null ? "" : o.Sex;
info.Age = o.Age == null ? "" : o.Age;
info.Notes = o.Notes == null ? "" : o.Notes;
return info;
}
public static function openDatabase(file:File):void
{
var newDB:Boolean = true;
if (file.exists)
newDB = false;
_sqlConnection = new SQLConnection();
_sqlConnection.open(file);
if (newDB)
{
createDatabase();
populateDatabase();
}
}
protected static function createDatabase():void
{
var sql:String =
"CREATE TABLE IF NOT EXISTS notes ( "+
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title VARCHAR(50), " +
"time VARCHAR(50), " +
"message VARCHAR(200))"
"CREATE TABLE IF NOT EXISTS members ( "+
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title VARCHAR(50), " +
"time VARCHAR(50), " +
"message VARCHAR(200))"
;
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
}
protected static function populateDatabase():void
{
var file:File = File.applicationDirectory.resolvePath("assets/notes.xml");
if (!file.exists) return;
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
var xml:XML = XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();
for each (var n:XML in xml.note)
{
var note:Dish = new Dish();
note.id = n.id;
note.title = n.title;
note.time = n.time;
note.message = n.message;
addNote(note);
}
}
}
}
and
member.as
package model
{
import mx.collections.ArrayCollection;
import mx.core.IUID;
[Bindable]
public class Member implements IUID
{
public var ID:int;
public var FirstName:String;
public var FamilyName:String;
public var Sex:String;
public var AgeID:int;
public var Notes:String;
public var Fname:String;
public var Famname:String;
public var Age:String;
public function get uid(): String {
return ID.toString();
}
public function set uid(value: String): void {
ID = parseInt(value);
}
}
}
Your SQL command is:
UPDATE Members SET FirstName=?, FamilyName=?, Sex=?, Age=?, Notes=? WHERE ID=?
But you are setting only the parameters for the five fields to be updated:
stmt.parameters[0] = note.FirstName;
stmt.parameters[1] = note.FamilyName;
stmt.parameters[2] = note.Sex;
stmt.parameters[3] = note.Age;
stmt.parameters[4] = note.Notes;
You also have to set the ID value.

Flash Builder Mobile 4.5 - Populate a list with data sqlite

`
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import spark.events.ViewNavigatorEvent;
protected var sqlConnection:SQLConnection;
protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void
{
sqlConnection = new SQLConnection();
sqlConnection.open(File.applicationStorageDirectory.resolvePath("euro.db"));
getAllGiberish();
}
protected function getAllGiberish():void
{
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = "SELECT esteso FROM generale GROUP BY nazione, esteso HAVING nazione = 'Austria'";
stmt.execute();
list.dataProvider = new ArrayCollection(stmt.getResult().data);
}
]]>
</fx:Script>
<s:List id="list" x="4" y="5" width="306" height="274" />
because I do not get any data in the list? What did I do wrong?
I have 4 fields in the generale table id, valore, moneta, esteso
I am no expert but I first thought the SQL statement may be malformed, HAVING I thought was used for aggregate functions, so would
SELECT esteso FROM generale WHERE nazione = 'Austria' GROUP BY nazione, esteso;
Although I just noticed this is from Aug 23 and you probably have sorted it already.
Jacko

How to get selected values (using checkBox) from DataGrid in flex

i have a datagrid which is getting values from a XML file (getting this xml file from database using PHP and HTTP request in flex). i have created a checkbox in every row in data grid. and here is my requirement:
i want to select tow or three check-box and would like to get all the values form that particular ROWs in some form , prefered arraycollection (such that i can pass this array directly to a bar chart) .. can some one help me as i am new to flex .
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="siteData.send()">
<mx:Script>
<![CDATA[
import mx.collections.XMLListCollection;
import mx.controls.*;
import mx.events.ListEvent;
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;
[Bindable] private var fullXML:XMLList;
private function contentHandler(evt:ResultEvent):void{
fullXML = evt.result.values;
}
]]>
</mx:Script>
<mx:VBox>
<mx:Label text="This Data Grid is loading the full XML file"/>
<mx:DataGrid width="600" id="datagrid" dataProvider="{fullXML}">
<mx:columns>
<mx:DataGridColumn headerText="Select">
<mx:itemRenderer>
<mx:Component>
<mx:HBox horizontalAlign="center">
<mx:CheckBox id="check"/>
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
<mx:DataGridColumn dataField="release_version" headerText="Release"/>
<mx:DataGridColumn dataField="build" headerText="build"/>
<mx:DataGridColumn dataField="time_login" headerText="time_login"/>
<mx:DataGridColumn dataField="time_tunnel" headerText="time_tunnel"/>
<mx:DataGridColumn dataField="rate_login" headerText="time_tunnel"/>
<mx:DataGridColumn dataField="rate_tunnel" headerText="rate_tunnel"/>
</mx:columns>
</mx:DataGrid>
</mx:VBox>
<mx:HTTPService url="http://localhost/php_genxml.php" id="siteData" result="contentHandler(event)" resultFormat="e4x"/>
</mx:Applicaton>
i want to select some check box and want to get the values of all the fields in data-grid correspond to that check-box, can some one help me how to get the selected values (selected values of check-box) in flex and action script.
<mx:itemRenderer>
<mx:Component>
<mx:HBox horizontalAlign="center" verticalAlign="middle">
<mx:Script>
<![CDATA[
var objTemp:Object = new Object();
override public function set data(value:Object):void
{
if(value != null)
{
var xml:XML = XML(value);
super.data = value;
objTemp = outerDocument.xmlToObject(xml.toString());
if(objTemp.story['quiz_score'] != null)
{
chkAssignment.visible = false;
}
else
{
chkAssignment.visible = true;
}
if(objTemp.story.is_selected == false)
{
chkAssignment.selected = false;
}
else
{
chkAssignment.selected = true;
}
}
}
private function deleteAssignment():void
{
if(chkAssignment.selected)
{
outerDocument.isChanged = true;
objTemp.story.is_selected = true;
var xml:XML = outerDocument.objectToXML(objTemp,"record");
var xmlList:XMLList = xml.children();
xml = xmlList[0] as XML;
outerDocument.dgListeningLog.dataProvider[outerDocument.dgListeningLog.selectedIndex] = xml;
outerDocument.arrAssignment.push({"story_name": XML(outerDocument.dgListeningLog.selectedItem).story_title.toString() ,"student_assignmentId": XML(outerDocument.dgListeningLog.selectedItem).assignment_id.toString(),"session_key": XML(outerDocument.dgListeningLog.selectedItem).session_key.toString(),"selectedIndex": outerDocument.dgListeningLog.selectedIndex.toString()});
}
else
{
outerDocument.isChanged = true;
objTemp.story.is_selected = false;
var xml:XML = outerDocument.objectToXML(objTemp,"record");
var xmlList:XMLList = xml.children();
xml = xmlList[0] as XML;
outerDocument.dgListeningLog.dataProvider[outerDocument.dgListeningLog.selectedIndex] = xml;
for(var i:int =0; i < outerDocument.arrAssignment.length; i++)
{
if(outerDocument.arrAssignment[i].selectedIndex == outerDocument.dgListeningLog.selectedIndex)
{
outerDocument.arrAssignment.splice(i,1);
break;
}
}
}
}
]]>
</mx:Script>
<mx:CheckBox id="chkAssignment" change="{deleteAssignment();}"/>
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
here i am storing the selected value or array in another array and when clicking on the remove button it will check and delete the value from the main array that is data provider of the dataGrid.
If you are facing the problem when scrolling the datagrid CheckBox shows wrong value than copy following method from code:
override public function set data(value:Object):void
there are mainly two functions used...
public function objectToXML(obj:Object, qname:String):XML
{
var qName:QName = new QName(qname);
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;
}
public function xmlToObject(value:String):Object
{
var xmlStr:String = value.toString();
var xmlDoc:XMLDocument = new XMLDocument(xmlStr);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
return resultObj;
}

Flex/Actionscript - capturing canvas bitmap with dynamically placed elements

I'm attempting to find overlap between elements on a flex canvas, an adaptation of
http://www.gskinner.com/blog/archives/2005/08/flash_8_shape_b.html
The attempt here is to place some text and figure overlap with previously placed text.
The simple example below illustrates the problem.
Both
ImageSnapshot.captureBitmapData(canvas);
or
BitmapData.draw(canvas);
do not seem to capture the elements placed on the canvas dynamically.
Any clues on how I can accomplish this?
Thanks in advance for any help.
-vivek
<?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" minWidth="955" minHeight="600"
creationComplete="init()">
<fx:Script>
<![CDATA[
import mx.controls.Image;
import mx.controls.Text;
import mx.graphics.ImageSnapshot;
public function init():void {
var l:Label = new Label();
l.text = 'Dynamic Label!';
l.x = text.x+50;
l.y = text.y;
canvas1.addElement(l);
var bounds:Rectangle = text.getBounds(this);
trace(bounds.top + ',' + bounds.left + ',' + bounds.width + ',' + bounds.height);
var bmd:BitmapData = new BitmapData(text.width, text.height);
bmd.draw(text);
var bm:Bitmap = new Bitmap(bmd);
var img:Image = new Image();
img.source = bm;
img.x = 0;
img.y = 20;
canvas2.addChild(img);
var c2:BitmapData = ImageSnapshot.captureBitmapData(canvas1);
var bmd2:BitmapData = new BitmapData(text.width,text.height);
bmd2.copyPixels(c2,bounds,new Point(0,0));
var bm2:Bitmap = new Bitmap(bmd2);
var img2:Image = new Image();
img2.source = bm2;
img2.x = 0;
img2.y = 50;
canvas2.addChild(img2);
var c3:BitmapData = new BitmapData(canvas1.width, canvas1.height);
c3.draw(canvas1);
var bmd3:BitmapData = new BitmapData(text.width,text.height);
bmd3.copyPixels(c3,bounds,new Point(0,0));
var bm3:Bitmap = new Bitmap(bmd2);
var img3:Image = new Image();
img3.source = bm3;
img3.x = 0;
img3.y = 50;
canvas3.addChild(img3);
}
]]>
</fx:Script>
<mx:Canvas id="canvas1" width="400" height="100" backgroundColor="#FF0000">
<s:Label id="text" x="200" y="50" text="This is a test"/>
</mx:Canvas>
<mx:Canvas id="canvas2" y="100" width="400" height="100" backgroundColor="#00FF00"/>
<mx:Canvas id="canvas3" y="200" width="400" height="100" backgroundColor="#0000FF"/>
</s:Application>
Calling addChild doesn't make the component immediately visible/available within its parent. You need the creation process to complete before you grab the bitmap, which involves multiple phases/events. Put your grabbing code into a separate method and call it AFTER the creation process completes for your dynamically created component. Do that by using the callLater method, which will put your method call at the end of the event queue. Here's your code with callLater added (not that pretty, but hopefully it gets the point across):
<?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" minWidth="955" minHeight="600"
creationComplete="init()">
<fx:Script>
<![CDATA[
import mx.controls.Image;
import mx.controls.Text;
import mx.graphics.ImageSnapshot;
public function init():void {
var l:Label = new Label();
l.text = 'Dynamic Label!';
l.x = text.x+50;
l.y = text.y;
canvas1.addElement(l);
this.callLater(addRect);
}
private function addRect():void {
var bounds:Rectangle = text.getBounds(this);
trace(bounds.top + ',' + bounds.left + ',' + bounds.width + ',' + bounds.height);
var bmd:BitmapData = new BitmapData(text.width, text.height);
bmd.draw(text);
var bm:Bitmap = new Bitmap(bmd);
var img:Image = new Image();
img.source = bm;
img.x = 0;
img.y = 20;
canvas2.addChild(img);
var c2:BitmapData = ImageSnapshot.captureBitmapData(canvas1);
var bmd2:BitmapData = new BitmapData(text.width,text.height);
bmd2.copyPixels(c2,bounds,new Point(0,0));
var bm2:Bitmap = new Bitmap(bmd2);
var img2:Image = new Image();
img2.source = bm2;
img2.x = 0;
img2.y = 50;
canvas2.addChild(img2);
var c3:BitmapData = new BitmapData(canvas1.width, canvas1.height);
c3.draw(canvas1);
var bmd3:BitmapData = new BitmapData(text.width,text.height);
bmd3.copyPixels(c3,bounds,new Point(0,0));
var bm3:Bitmap = new Bitmap(bmd2);
var img3:Image = new Image();
img3.source = bm3;
img3.x = 0;
img3.y = 50;
canvas3.addChild(img3);
}
]]>
</fx:Script>
<mx:Canvas id="canvas1" width="400" height="100" backgroundColor="#FF0000">
<s:Label id="text" x="200" y="50" text="This is a test"/>
</mx:Canvas>
<mx:Canvas id="canvas2" y="100" width="400" height="100" backgroundColor="#00FF00"/>
<mx:Canvas id="canvas3" y="200" width="400" height="100" backgroundColor="#0000FF"/>
</s:Application>

Resources