Transcript
Page 1: BlackBerry DevCon 2011 - COM34

Aplicaciones orientadas a datos en BlackBerry PlayBook

Mariano Carrizo

COM34

Octubre 18 - 20, 2011

Page 2: BlackBerry DevCon 2011 - COM34

Agenda

Descarga simple de datos Flex data components Protocolo AMF Remote Objects Sistema de archivos Bases de datos

@kiwox– 2

Page 3: BlackBerry DevCon 2011 - COM34

Descarga simple de datos

URLLoader

Page 4: BlackBerry DevCon 2011 - COM34

URLLoaderEl Camino Simple

Clase nativa ActionScript 3 Permite la descarga de contenidos en varios formatos

Text URL encoded variables Binary

Informa el progreso de descarga URLLoader.bytesLoaded URLLoader.bytesTotal

Dispone los datos una vez completada la descarga

@kiwox– 4

Page 5: BlackBerry DevCon 2011 - COM34

URLLoaderEjemplo

protected var ldr:URLLoader;

protected function loadData():void {ldr = new URLLoader();ldr.addEventListener(Event.COMPLETE, onDataComplete);ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);try {

ldr.load(new URLRequest("datos.php"));} catch(e:Error) {

trace("Error al descargar datos");}

}@kiwox– 5

Page 6: BlackBerry DevCon 2011 - COM34

URLLoaderEjemplo

protected function onDataComplete(event:Event):void {trace(ldr.data);

}

protected function onError(event:IOErrorEvent):void {trace("Error: "+event.errorID);

}

@kiwox– 6

Page 7: BlackBerry DevCon 2011 - COM34

URLLoaderDatos en Formato XML

protected var xmlData:XML;

protected function onDataComplete(event:Event):void {xmlData = XML(ldr.data);for(var i:String in xmlData.item) {

trace(xmlData.item[i].titulo);}

}

@kiwox– 7

Page 8: BlackBerry DevCon 2011 - COM34

URLLoaderDatos en Formato Binario

ldr = new URLLoader();ldr.dataFormat = URLLoaderDataFormat.BINARY;ldr.addEventListener(Event.COMPLETE, onDataComplete);ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);ldr.addEventListener(ProgressEvent.PROGRESS, onProgress);

try {ldr.load(new URLRequest("imagen.png"));

} catch(e:Error) {trace("Error al descargar imagen");

}

@kiwox– 8

Page 9: BlackBerry DevCon 2011 - COM34

Flex Data Components

Abstrayendo Las Tareas

Page 10: BlackBerry DevCon 2011 - COM34

Flex data componentsAbstrayendo Las Tareas

Simplifican la intermediación con el servidor Disponen los datos listos para usarlos Admiten formatos más complejos

XML JSON AMF Objeto/Array

Permiten enlazar a componentes visuales List, TextArea, etc.

@kiwox– 10

Page 11: BlackBerry DevCon 2011 - COM34

Flex data componentsHTTPService

Obtiene datos directos de estilo REST Inicia la llamada con el método send() El resultado estará disponible en la propiedad lastResult

@kiwox– 11

Page 12: BlackBerry DevCon 2011 - COM34

Flex data componentsHTTPService

<fx:Declarations><s:HTTPService id="servicio"

url="miServicio.php" /></fx:Declarations>

<s:Button label="Descargar" click="servicio.send()" />

<s:List dataProvider="{servicio.lastResult.rss.channel.item}" />

@kiwox– 12

Page 13: BlackBerry DevCon 2011 - COM34

Flex data componentsWebService

Interactúa con servicios WSDL Soporta protocolo SOAP Permite el envío de parámetros a métodos específicos Los resultados pueden ser enlazados o esperados en

métodos callBack Podemos configurar cada operación con elementos

<s:operation>

@kiwox– 13

Page 14: BlackBerry DevCon 2011 - COM34

Flex data componentsWebService

<s:WebService id="servicio" wsdl="http://ws.invesbot.com/stockquotes.asmx?WSDL">

<s:operation name="GetQuote" resultFormat="object" result="quoteResultHandler(event)">

<s:request><symbol>SYMBOL</symbol>

</s:request></s:operation>

</s:WebService>

@kiwox– 14

Page 15: BlackBerry DevCon 2011 - COM34

Demo

Acceso a Datos Remotos

@kiwox– 15

Page 16: BlackBerry DevCon 2011 - COM34

Protocolo AMF

Transferencia Binaria de Datos

Page 17: BlackBerry DevCon 2011 - COM34

Protocolo AMFTransferencia Binaria de Datos

Active Message Format Formato nativo ActionScript

ActionScript 2: AMF0 ActionScript 3: AMF3

Soporta datos primitivos y compuestos String, Number, Null, Boolean… Object, Array, XML, ByteArray Objetos personalizados (ValueObjects)

@kiwox– 17Especificación AMF3: http://goo.gl/b3qbk

Page 18: BlackBerry DevCon 2011 - COM34

Protocolo AMFTransferencia Binaria de Datos

Desde ActionScript utilizando NetStream En conjunto con Flash Media Server bajo protocolo rtmp:/ Permite instanciar objetos remotos (servidor) Soporte disponible en la mayoría de servidores

@kiwox– 18

Page 19: BlackBerry DevCon 2011 - COM34

Protocolo AMFTransferencia Binaria de Datos

var netConnection:NetConnection = new NetConnection();var responder:Responder = new Responder();netConnection.connect(“http://localhost/Amfphp/”);netConnection.call(“DataService/getRecords”, responder);

@kiwox– 19

Page 20: BlackBerry DevCon 2011 - COM34

Remote Objects

@kiwox– 20

Ser

vido

r

Clases PHP

<s:RemoteObject id="servicio” fault="faultHandler(event)” showBusyCursor="true” destination="zend" />

servicio.getAll()

ObjectVO[]

Page 21: BlackBerry DevCon 2011 - COM34

Remote Objectsservices-config.xml

@kiwox– 21

<services-config> <services> <service id="zend-service" class="flex.messaging.services.RemotingService” messageTypes="flex.messaging.messages.RemotingMessage"> <destination id="zend"> <channels> <channel ref="zend-endpoint"/> </channels> <properties> <source>*</source> </properties> </destination> </service> </services> <channels> <channel-definition id="zend-endpoint” class="mx.messaging.channels.AMFChannel"> <endpoint uri="http://example.com/server.php” class="flex.messaging.endpoints.AMFEndpoint"/> </channel-definition> </channels></services-config>

Page 22: BlackBerry DevCon 2011 - COM34

Persistencia de Datos

Almacenamiento en el Dispositivo

Page 23: BlackBerry DevCon 2011 - COM34

Sistema de Archivos

File Localiza y resuelve punteros a archivos Permite consultar propiedades y existencia

FileStream Flujo de lectura/escritura de datos

Page 24: BlackBerry DevCon 2011 - COM34

Sistema de Archivos

@kiwox– 24

Localizar Recurso

Crear Flujo de Datos

Leer Datos Cerrar Flujo

Page 25: BlackBerry DevCon 2011 - COM34

Sistema de Archivos

@kiwox– 25

Localizar Recurso

Crear Flujo de Datos

Escribir Datos Cerrar Flujo

Page 26: BlackBerry DevCon 2011 - COM34

Sistema de archivos

@kiwox– 26

var archivo:File = File.documentsDirectory.resolvePath(“datos/listado.xml”);

if(archivo.exists) {…

}

Page 27: BlackBerry DevCon 2011 - COM34

Directorios

File.applicationDirectory <appDir>/app/air/

File.applicationStorageDirectory <appDir>/data/

File.documentsDirectory File.desktopDirectory

/shared/documents/

@kiwox– 27

Page 28: BlackBerry DevCon 2011 - COM34

FileStream

@kiwox– 28

var fs:FileStream = new FileStream();fs.open(archivo, FileMode.READ)

FileMode.READFileMode.WRITEFileMode.APPENDFileMode.UPDATE

Page 29: BlackBerry DevCon 2011 - COM34

FileStream

@kiwox– 29

var datos:File = File.applicationStorageDirectory.resolvePath("datos.txt");

var fs:FileStream = new FileStream();

fs.open(datos, FileMode.WRITE);

try {

fs.writeUTFBytes("Hola mundo");

} catch(e:Error) {

trace("Error escribiendo");

}

fs.close();

Page 30: BlackBerry DevCon 2011 - COM34

FileStream

@kiwox– 30

var datos:File = File.applicationStorageDirectory.resolvePath("datos.txt");

var fs:FileStream = new FileStream();

fs.addEventListener(Event.COMPLETE, completeHandler);

fs.openAsync(datos, FileMode.READ);

var str:String = "";

function completeHandler(event:Event):void {

str = fs.readUTFBytes(fs.bytesAvailable);

}

Page 31: BlackBerry DevCon 2011 - COM34

FileStream

@kiwox– 31

var datos:File = File.applicationStorageDirectory.resolvePath("datos.txt");

var fs:FileStream = new FileStream();

fs.addEventListener(ProgressEvent.PROGRESS, progressHandler);

fs.addEventListener(Event.COMPLETE, completeHandler);

fs.openAsync(datos, FileMode.READ);

var str:String = "";

function progressHandler(event:ProgressEvent):void {

str += fs.readUTFBytes(fs.bytesAvailable);

}

function completeHandler(event:Event):void {

trace("Datos listos");

}

Page 32: BlackBerry DevCon 2011 - COM34

Bases de Datos

SQLite en Adobe AIR

@kiwox– 32

Page 33: BlackBerry DevCon 2011 - COM34

SQLite

SQLConnection Objeto conector Localiza el recurso y maneja las transacciones

@kiwox– 33

Page 34: BlackBerry DevCon 2011 - COM34

SQLite

@kiwox– 34

var conn:SQLConnection = new SQLConnection(); conn.addEventListener(SQLEvent.OPEN, openHandler); conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); var folder:File = File.applicationStorageDirectory; var dbFile:File = folder.resolvePath("DBSample.db"); conn.openAsync(dbFile); function openHandler(event:SQLEvent):void { trace(”Base de datos abierta"); } function errorHandler(event:SQLErrorEvent):void { trace(“Error:”, event.error.message); trace(“Detalles:”, event.error.details); }

Page 35: BlackBerry DevCon 2011 - COM34

SQLite

@kiwox– 35

var conn:SQLConnection = new SQLConnection(); var folder:File = File.applicationStorageDirectory; var dbFile:File = folder.resolvePath("DBSample.db"); try { conn.open(dbFile); trace(”Base de datos abierta"); } catch (error:SQLError) { trace("Error:", error.message); trace(”Detalles:", error.details); }

Page 36: BlackBerry DevCon 2011 - COM34

SQLite

SQLStatement Transacciones individuales Pueden ser asincrónicas

@kiwox– 36

Page 37: BlackBerry DevCon 2011 - COM34

SQLite

@kiwox– 37

var createStmt:SQLStatement = new SQLStatement(); createStmt.sqlConnection = conn; var sql:String = "CREATE TABLE IF NOT EXISTS employees (" + " empId INTEGER PRIMARY KEY AUTOINCREMENT, " + " firstName TEXT, " + " lastName TEXT, " + " salary NUMERIC CHECK (salary > 0)" + ")"; createStmt.text = sql; createStmt.addEventListener(SQLEvent.RESULT, createResult); createStmt.addEventListener(SQLErrorEvent.ERROR, createError); createStmt.execute();

Page 38: BlackBerry DevCon 2011 - COM34

SQLite

@kiwox– 38

conn.open(dbFile, OpenMode.UPDATE); conn.begin(); var insertCustomer:SQLStatement = new SQLStatement(); insertCustomer.sqlConnection = conn;

insertCustomer.text = "INSERT INTO customers (firstName, lastName) " + "VALUES ('Bob', 'Jones')";

insertCustomer.execute();

var customerId:Number = insertCustomer.getResult().lastInsertRowID;

conn.commit();

Page 39: BlackBerry DevCon 2011 - COM34

SQLite

@kiwox– 39

var insertPhoneNumber:SQLStatement = new SQLStatement(); insertPhoneNumber.sqlConnection = conn;

insertPhoneNumber.text = "INSERT INTO customerPhoneNumbers (customerId, number) " + "VALUES (:customerId, '800-555-1234')";

insertPhoneNumber.parameters[":customerId"] = customerId;

insertPhoneNumber.execute(); conn.commit();

Page 40: BlackBerry DevCon 2011 - COM34

SQLite

@kiwox– 40

try {var insertPhoneNumber:SQLStatement = new SQLStatement(); insertPhoneNumber.sqlConnection = conn;

insertPhoneNumber.text = "INSERT INTO customerPhoneNumbers (customerId, number) " + "VALUES (:customerId, '800-555-1234')";

insertPhoneNumber.parameters[":customerId"] = customerId;

insertPhoneNumber.execute(); conn.commit(); } catch (error:SQLError) { conn.rollback(); }

Page 41: BlackBerry DevCon 2011 - COM34

SQLite

Bases de datos encriptadas Utilizan una llave en formato ByteArray

@kiwox– 41

public function open(reference:Object = null, openMode:String = "create", autoCompact:Boolean = false, pageSize:int = 1024, encryptionKey:ByteArray = null):void

Page 42: BlackBerry DevCon 2011 - COM34

SQLite

@kiwox– 42

var conn:SQLConnection = new SQLConnection(); var encryptionKey:ByteArray = new ByteArray(); encryptionKey.writeUTFBytes(”CadenaDe16Bytes"); conn.openAsync(dbFile, SQLMode.CREATE, null, false, 1024, encryptionKey);

Page 43: BlackBerry DevCon 2011 - COM34

Demo

Manejo de Datos

@kiwox– 43

Page 44: BlackBerry DevCon 2011 - COM34

Más Información…

Recursos Adobe DevNet: http://www.adobe.com/devnet/devices.html Tour de Flex: http://www.adobe.com/devnet/flex/tourdeflex.html Adobe TV: http://tv.adobe.com/ Libro Flex 4.5: http://goo.gl/RcKXJ

@kiwox– 44

Page 45: BlackBerry DevCon 2011 - COM34

¡Muchas Gracias!

Mariano Carrizo

COM34

Octubre 18 - 20, 2011


Top Related