First off I am new to using Flex, but I have pieced this app together with help from online tutorials and information. Basically my app is like a directory of names, addresses and so forth, but I also have additional fields of "week" and "day". What I am trying to do is have a list that shows only the names of, for example Week 1 - Monday. Below is some of the code I am using to help you understand what I am trying to do. I appreciate any help!
<s:List dataProvider="{AddDoctorDatabase.doctors()}" labelField="name" change="onDoctorSelected(event)"
left="0" right="0" top="0" bottom="0">
</s:List>
public static function doctors():ArrayCollection
{
var doctorList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, week, day, name, address, city, state, zip, phone FROM doctors";
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++) {
doctorList.addItem(processRow(result[index]));
}
}
}
return doctorList;
}
Adding a doctor
<s:SpinnerListContainer>
<s:SpinnerList id="weekField" width="100" height="75" labelField="week">
<s:ArrayList>
<fx:Object week="Week 1"/>
<fx:Object week="Week 2"/>
</s:ArrayList>
</s:SpinnerList>
</s:SpinnerListContainer>
<s:Label text="Select a day:"/>
<s:SpinnerListContainer>
<s:SpinnerList id="dayField" width="100" height="150" labelField="day">
<s:ArrayList>
<fx:Object day="Monday"/>
<fx:Object day="Tuesday"/>
<fx:Object day="Wednesday"/>
<fx:Object day="Thursday"/>
<fx:Object day="Friday"/>
</s:ArrayList>
</s:SpinnerList>
</s:SpinnerListContainer>
protected function onSave():void {
var newDoctor:AddDoctor = new AddDoctor();
newDoctor.week = weekField.selectedItem;
newDoctor.day = dayField.selectedItem;
newDoctor.name = nameField.text;
newDoctor.address = addressField.text;
newDoctor.city = cityField.text;
newDoctor.state = stateField.text;
newDoctor.zip = zipField.text;
newDoctor.phone = phoneField.text;
AddDoctorDatabase.addDoctor(newDoctor);
Assuming this is inspired by Christophe Coenraets's employee directory sample, you'd have to create a Doctor Class and set its public variable in the processRow function with your retrieved data before adding the newly created Doctor object in the ArrayCollection:
<fx:Script>
<![CDATA[
//Add this
[Bindable]
public var dList:ArrayCollection;
private function searchDoctorsClicked(event:MouseEvent):void
{
dList = getDoctorForWeekAndDay(weekField.selectedItem, dayField.selectedItem);
}
private function creationComplete_handler(event:Event):void
{
dList = getAllDoctors();
}
public function getAllDoctors():ArrayCollection
{
var doctorList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, week, day, name, address, city, state, zip, phone FROM doctors";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
for (var index:Number = 0; index < result.length; index++)
{
//doctorList.addItem(processRow(result[index]));
doctorList.addItem({result[index].week, result[index].day, result[index].name});
}
return doctorList;
}
else
{
return null;
}
}
public function processRow(o:Object):Doctor
{
var d:Doctor = new Doctor();
d.Name = o.name;
d.week = o.week;
d.day = o.day;
return d;
}
public class Doctor()
{
public function Doctor(){}
public var name:String;
public var week:String;
public var day:int;
}
//Call this one when they select a week and day and hit a button, or just
//on change of those options pass through the value/selectedItem from each list
public function getDoctorForWeekAndDay(chosenWeek:String, chosenDay:String):ArrayCollection
{
var doctorList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, week, day, name, address, city, state, zip, phone FROM doctors WHERE week='"+chosenWeek+"' AND day='"+chosenDay+"'";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
for (var index:Number = 0; index < result.length; index++)
{
doctorList.addItem(processRow(result[index]));
}
return doctorList;
}
else
{
return null;
}
}
]]>
</fx:Script>
<s:List dataProvider="{dList}" change="onDoctorSelected(event)" left="0" right="0" top="0" bottom="0">
<s:IconItemRenderer label="{week} - { day }" messageField="name" />
</s:List>
This should work, I think
I'm not an expert, but i think than this could help you!
<fx:Script>
<![CDATA[
//Add this
[Bindable]
public var dList:ArrayCollection;
private function searchDoctorsClicked(event:MouseEvent):void
{
dList = getDoctorForWeekAndDay(weekField.selectedItem, dayField.selectedItem);
}
private function creationComplete_handler(event:Event):void
{
dList = getAllDoctors();
}
public function getAllDoctors():ArrayCollection
{
var doctorList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, week, day, name, address, city, state, zip, phone FROM doctors";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
for (var index:Number = 0; index < result.length; index++)
{
//doctorList.addItem(processRow(result[index]));
doctorList.addItem({result[index].week, result[index].day, result[index].name});
}
return doctorList;
}
else
{
return null;
}
}
//Call this one when they select a week and day and hit a button, or just
//on change of those options pass through the value/selectedItem from each list
public function getDoctorForWeekAndDay(chosenWeek:String, chosenDay:String):ArrayCollection
{
var doctorList:ArrayCollection = new ArrayCollection();
var sql:String = "SELECT id, week, day, name, address, city, state, zip, phone FROM doctors WHERE week='"+chosenWeek+"' AND day='"+chosenDay+"'";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
for (var index:Number = 0; index < result.length; index++)
{
//doctorList.addItem(processRow(result[index]));
doctorList.addItem({result[index].week, result[index].day, result[index].name});
}
return doctorList;
}
else
{
return null;
}
}
]]>
</fx:Script>
<s:List dataProvider="{dList}" change="onDoctorSelected(event)" left="0" right="0" top="0" bottom="0">
<s:IconItemRenderer label="{week} - { day }" messageField="name" />
</s:List>
Related
I had created an android app (Employee Directory) in flash builder with SQLite database connection and having 4 tabs (view). I Just want that when I click on the Admin tab the Employee details from the database should be loaded. Below is my code.
EmployeeDirectory.mxml
<s:TabbedViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark">
<fx:Style>
s|ActionBar
{
chromeColor: #D3D3D3;
}
s|ActionBar #titleDisplay
{
color: #161616;
fontSize: 20;
fontWeight: normal;
fontFamily: "Microsoft Sans Serif";
}
s|TabbedViewNavigator #tabBar
{
chromeColor: #D3D3D3;
color: #161616;
fontFamily: "Microsoft Sans Serif";
iconPlacement:top;
}
</fx:Style>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function button1_clickHandler(event:MouseEvent):void {
// Switch to the first section in the application.
tabbedNavigator.selectedIndex = 0;
// Switch to the first view in the section.
ViewNavigator(tabbedNavigator.selectedNavigator).popToFirstView();
}
protected function BackBtn_clickHandler(event:MouseEvent):void {
// Switch to the first view in the section.
ViewNavigator(tabbedNavigator.selectedNavigator).popView();
}
]]>
</fx:Script>
<s:navigators>
<s:ViewNavigator label="Home" width="100%" height="100%"
firstView="views.HomeView" icon="#Embed('assets/Home1.png')">
</s:ViewNavigator>
<s:ViewNavigator label="Admin" width="100%" height="100%"
firstView="views.AdminView" icon="#Embed('assets/admin.png')">
<s:navigationContent>
<s:Button icon="#Embed('assets/home.png')"
click="button1_clickHandler(event)"/>
<s:Button icon="#Embed('assets/back2.png')"
click="BackBtn_clickHandler(event)"/>
</s:navigationContent>
</s:ViewNavigator>
<s:ViewNavigator label="Consultants" width="100%" height="100%"
firstView="views.ConsultantsView" icon="#Embed('assets/doctor.jpg')">
<s:navigationContent>
<s:Button icon="#Embed('assets/home.png')"
click="button1_clickHandler(event)"/>
</s:navigationContent>
</s:ViewNavigator>
<s:ViewNavigator label="Extn." width="100%" height="100%"
firstView="views.ExtnView" icon="#Embed('assets/ext.png')">
<s:navigationContent>
<s:Button icon="#Embed('assets/home.png')"
click="button1_clickHandler(event)"/>
<s:Button label="Back"
click="BackBtn_clickHandler(event)"/>
</s:navigationContent>
</s:ViewNavigator>
</s:navigators>
<fx:Declarations>
</fx:Declarations>
</s:TabbedViewNavigatorApplication>
AdminView
<?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="Admin" xmlns:dao="dao.*">
<fx:Declarations>
<dao:EmployeeDAO id="srv"/>
</fx:Declarations>
<s:titleContent>
<s:TextInput id="key" width="100%"/>
</s:titleContent>
<s:actionContent>
<s:Button icon="#Embed('assets/search.png')"
click="data=srv.findByName(key.text)"/>
</s:actionContent>
<s:List id="list" top="0" bottom="0" left="0" right="0"
dataProvider="{data}"
change="navigator.pushView(Employeedetails, list.selectedItem)">
<s:itemRenderer>
<fx:Component>
<s:IconItemRenderer
label="{data.firstName} {data.lastName}"
messageField="title"/>
</fx:Component>
</s:itemRenderer>
</s:List>
</s:View>
EmployeeDAO
package dao
{
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import mx.collections.ArrayCollection;
public class EmployeeDAO
{
public function getItem(id:int):Employee
{
var sql:String = "SELECT id, firstName, lastName, title, department,
city, email, officePhone, cellPhone, managerId, picture FROM employee 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 function findByManager(managerId:int):ArrayCollection
{
var sql:String = "SELECT * FROM employee WHERE managerId=? ORDER BY
lastName, firstName";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = managerId;
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
var list:ArrayCollection = new ArrayCollection();
for (var i:int=0; i<result.length; i++)
{
list.addItem(processRow(result[i]));
}
return list;
}
else
{
return null;
}
}
public function findByName(searchKey:String):ArrayCollection
{
var sql:String = "SELECT * FROM employee WHERE firstName || ' ' ||
lastName || ' ' || department LIKE ? and managerId in ('1','2') ORDER BY id,
managerId, firstName, lastName";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = "%" + searchKey + "%";
stmt.execute();
var result:Array = stmt.getResult().data;
if (result)
{
var list:ArrayCollection = new ArrayCollection();
for (var i:int=0; i<result.length; i++)
{
list.addItem(processRow(result[i]));
}
return list;
}
else
{
return null;
}
}
public function create(employee:Employee):void
{
trace(employee.firstName);
if (employee.manager) trace(employee.manager.id);
var sql:String =
"INSERT INTO employee (id, firstName, lastName, title,
department, managerId, city, officePhone, cellPhone, email, picture) " +
"VALUES (?,?,?,?,?,?,?,?,?,?,?)";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.parameters[0] = employee.id;
stmt.parameters[1] = employee.firstName;
stmt.parameters[2] = employee.lastName;
stmt.parameters[3] = employee.title;
stmt.parameters[4] = employee.department;
stmt.parameters[5] = employee.manager ? employee.manager.id : null;
stmt.parameters[6] = employee.city;
stmt.parameters[7] = employee.officePhone;
stmt.parameters[8] = employee.cellPhone;
stmt.parameters[9] = employee.email;
stmt.parameters[10] = employee.picture;
stmt.execute();
employee.loaded = true;
}
protected function processRow(o:Object):Employee
{
var employee:Employee = new Employee();
employee.id = o.id;
employee.firstName = o.firstName == null ? "" : o.firstName;
employee.lastName = o.lastName == null ? "" : o.lastName;
employee.title = o.title == null ? "" : o.title;
employee.department = o.department == null ? "" : o.department;
employee.city = o.city == null ? "" : o.city;
employee.email = o.email == null ? "" : o.email;
employee.officePhone = o.officePhone == null ? "" : o.officePhone;
employee.cellPhone = o.cellPhone == null ? "" : o.cellPhone;
employee.picture = o.picture;
if (o.managerId != null)
{
var manager:Employee = new Employee();
manager.id = o.managerId;
employee.manager = manager;
}
employee.loaded = true;
return employee;
}
public static var _sqlConnection:SQLConnection;
public function get sqlConnection():SQLConnection
{
if (_sqlConnection) return _sqlConnection;
var file:File =
File.applicationDirectory.resolvePath("assets/Employee.db");
var fileExists:Boolean = file.exists;
_sqlConnection = new SQLConnection();
_sqlConnection.open(file);
if (!fileExists)
{
createDatabase();
populateDatabase();
}
return _sqlConnection;
}
protected function createDatabase():void
{
var sql:String =
"CREATE TABLE IF NOT EXISTS employee ( "+
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"firstName VARCHAR(50), " +
"lastName VARCHAR(50), " +
"title VARCHAR(50), " +
"department VARCHAR(50), " +
"managerId INTEGER, " +
"city VARCHAR(50), " +
"officePhone VARCHAR(30), " +
"cellPhone VARCHAR(30), " +
"email VARCHAR(30), " +
"picture VARCHAR(200))";
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = sql;
stmt.execute();
}
protected function populateDatabase():void
{
var file:File =
File.applicationDirectory.resolvePath("assets/employees.xml");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
var xml:XML = XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();
var employeeDAO:EmployeeDAO = new EmployeeDAO();
for each (var emp:XML in xml.employee)
{
var employee:Employee = new Employee();
employee.id = emp.id;
employee.firstName = emp.firstName;
employee.lastName = emp.lastName;
employee.title = emp.title;
employee.department = emp.department;
employee.city = emp.city;
employee.officePhone = emp.officePhone;
employee.cellPhone = emp.cellPhone;
employee.email = emp.email;
employee.picture = emp.picture;
if (emp.managerId>0)
{
employee.manager = new Employee();
employee.manager.id = emp.managerId;
}
employeeDAO.create(employee);
}
}
}
}
The below is my screen
this is the home screen and after clicking on admin tab the data should be
displayed. Currently the data is displayed after clicking on search button in
admin view
[After clicking on admin tab from home screen][2]
The data should be displayed like this
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
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.
`
<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
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>