SQLite problem - Solved


#1

I’ve set up an app, installed the cordova-sqlite-storage plugin created a table ‘name’, then inserted into that table one record with name = ‘John Doh’. I then run an SQL select query against the table and try to print out the value of name in an alert.

The resulting alert when run using ionic serve is as expected, an array with 1 object [{id:1,name:‘John Doh’}] Length: 1

The resulting alert when run using ionic emulate android is [null] length: 1

`
import {App, Platform, Storage, SqlStorage} from ‘ionic-framework/ionic’;
import {TabsPage} from ‘./pages/tabs/tabs’;
import * as _ from ‘lodash/lodash’;

@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
  static get parameters() {
    return [[Platform]];
  }

  constructor(Platform) {
    this.rootPage = TabsPage;
    this.platform = Platform;

    this.init();
  }

  init() {
    this.platform.ready().then(() => {
      this.storage = new Storage(SqlStorage)
      this.storage.query('CREATE TABLE IF NOT EXISTS name (id INTEGER PRIMARY KEY     AUTOINCREMENT, name TEXT)')
        .then((data) => {
          this.storage.query("INSERT INTO name (name) VALUES ('John Doh')").then((data) => {})
          this.storage.query("SELECT * FROM name").then((data) => {
            if(data.res.rows.length > 0) {       
             var i = _.map(data.res.rows, (record) => {  
            return record;            
          })
        };
        alert(JSON.stringify(i) + ' Length: ' + i.length);
      })
    }, (error) => {
      console.log("ERROR -> " + JSON.stringify(error.err));
    });  
});    
}
}

`

Does anybody see my error? I’m guessing it’s obvious, yet it’s invisible to me!


#2

I’ve spent a couple hours chasing this problem down and only moments after posting this ridiculous question did I find the answer! The issue was in using the lodash _.map method in converting the returned object into an array, once I changed this to the more verbose if statement all is well.

It’s still strange how it worked fine using _.map in Chrome but not when emulated, which unless I’m completely wrong here uses a Chrome webview?

I hope nobody wasted any effort on this, and I’ll leave it here in case anybody else makes the same mistake!