Search code examples
stringapache-flexsqliteairflash-builder

Adobe Air: convert sqlite's result [object Object] to String?


I am currently trying to do retrieve text from sqlite. I see that the amount of data requested do come correctly, but content, on the other hand, seems to be in an incorrect format. I've tried some conversion:

var data:Array = sqls.getResult().data;

var stData:String = String(data[0]);

Alert.show(stData); // <--- displays "[object Object]"

String conversion does not seem to do what I want. I simply want the text from the sqlite database. How can I convert the [object Object] to the correct string in this case?


Solution

  • Irrespective of what rows are returned (with(out)) specifying columns, unless the itemClass property of the SQLStatement is defined, it will always return an anonymous object. This is essentially how remoting works with AMF.

    There are two things you can do (depending on the complexity of your project):

    1. Specify an SQLStatement.itemClass - this will define & popuplate the results of the return with public accessors (either var or get/set) with the same name as the column name.
    2. If left as anonymous - the column names are attached to the object in which you iterate the object just as you would if it was defined.

    Super basic example:

    //SQL table schema
    CREATE TABLE accounts (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      num INTEGER NOT NULL,
      name TEXT NOT NULL,
      last_update DATE
    );
    
    //Define an Account class:
    public class Account {
        public var id:int;
        public var num:int;
        public var name:String;
        public var last_update:Date;
    }
    
    //A statement to execute to get all accounts returned as an array of "Account"
    var statement:SQLStatement = new SQLStatement();
        statement.sqlConnection = myConn;
        statement.itemClass = Account;
        statement.text = 'SELECT * FROM accounts';
        statement.addEventListener(SQLEvent.RESULT, onResults);
        statement.execute();
    
     protected function onResults(event:SQLEvent):void
     {
          var statement:SQLStatement = SQLStatement(event.currentTarget);
          var results:SQLResult = statement.getResult();
          for each (var account:Account in results)
          {
              //do something useful like populate a model, grid, etc...
          }
     }
    
    
     //Anonymous objects would iterate much the same way -when an item class isn't defined
     protected function onResults(event:SQLEvent):void
     {
          var statement:SQLStatement = SQLStatement(event.currentTarget);
          var results:SQLResult = statement.getResult();
          for each (var account:Object in results)
          {
              //our 'Object' will have properties: id, num, name, last_update
              //do something useful like populate a model, grid, etc...
          }
     }