Flex/Actionscript - capturing canvas bitmap with dynamically placed elements - apache-flex

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>

Related

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

Connecting Flex to SQLite

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>

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 checkbox control in datagrid

In my flex application im using a datagrid which has
checkbox itemrenderer column
im using the following code
<mx:DataGridColumn headerText="Select" dataField="isSelect" editable="false" textAlign="center" >
<mx:itemRenderer >
<mx:Component>
<mx:CheckBox selected="{data.isSelect}" change="outerDocument.addDetail(data)" >
</mx:CheckBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
<mx:DataGridColumn headerText="FirstName" dataField="firstName" color="black" editable="false" width="125" />
<mx:DataGridColumn headerText="SecondName" dataField="lsecondName" color="black" editable="false" width="125"/>
after selecting the checkbox and im saving the details in my DB.
now,
when i come for fetching data the selected details from the db should be selected in checkbox.
how can i differentiate selected record and unselected Record.?? thanxx in advance
<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
Are you sure, that data provided to row itemRenderer has correct isSelect property? Try to trace it.

Resources