0

I have been trying to make a simple table and then insert data into it to develop an understanding that how Ionic 2 framework works but I'm stuck with the problem and unable to resolve it. I have tried different google solutions but none of them worked.

Note: I'm new to Ionic 2 and originally native Android Developer.

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
/**
 * Generated class for the AddProductsPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-add-products',
  templateUrl: 'add-products.html',

})
export class AddProductsPage {
  productName: string;
  sqlstorage: SQLite;
  items: Array<Object>;
  db: SQLiteObject;
  mesg: string;
  constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController, public platform: Platform) {


    this.platform.ready().then(() => {
      this.sqlstorage = new SQLite();

      this.sqlstorage.create({ name: "test.db", location: "default" }).then(() => {
        console.log("SuccessDB");
        this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
        // this.createTables();
      }, (err) => {
        console.log("DB !!! ", err);
      });
    });
  }
  presentToast() {
    let toast = this.toastCtrl.create({
      message: this.mesg,
      duration: 3000,
      position: 'top'
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }
  addProduct() {


    this.addItem("insert into product (productName) values(?)", this.productName);
    this.findAll();
  }

  public createTables() {       
    this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
  }

  public addItem(q: string, param: string) {
    this.db.executeSql(q, param).then((data) => {
      console.log("Success");
    }, (e) => {
      console.log("Error :  " + JSON.stringify(e.err));
    });
  }

  public findAll() {
    this.db.executeSql("SELECT * FROM items", []).then((data) => {
      this.items = [];
      if (data.rows.length > 0) {
        for (var i = 0; i < data.rows.length; i++) {
          this.items.push(data.rows.item(i));
          this.mesg = data.rows.item(i);
          console.log(this.mesg);
        }
      }
    }, (e) => {
      this.mesg = "Errot: " + JSON.stringify(e);
      console.log("Errot: " + JSON.stringify(e));
    });
    this.presentToast();
  }
}

Heres the error from Device

OPEN database: test.db SQLitePlugin.js:175
new transaction is waiting for open operation SQLitePlugin.js:106
OPEN database: test.db - OK 
ERROR 
Error {rejection: TypeError, promise: t, zone: r, task: t}
message: "Uncaught (in promise): TypeError: Cannot call method 'executeSql' of undefined↵TypeError: Cannot call method 'executeSql' of undefined↵    at AddProductsPage.createTables (file:///android_asset/www/build/main.js:58248:17)↵    at file:///android_asset/www/build/main.js:58226:23↵    at t.invoke (file:///android_asset/www/build/polyfills.js:3:9283)↵    at Object.inner.inner.fork.onInvoke (file:///android_asset/www/build/main.js:4649:37)↵    at t.invoke (file:///android_asset/www/build/polyfills.js:3:9223)↵    at r.run (file:///android_asset/www/build/polyfills.js:3:4452)↵    at file:///android_asset/www/build/polyfills.js:3:14076↵    at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:9967)↵    at Object.inner.inner.fork.onInvokeTask (file:///android_asset/www/build/main.js:4640:37)↵    at t.invokeTask (file:///android_asset/www/build/polyfills.js:3:9888)"
promise: t
rejection: TypeError
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
task: t
zone: r
__proto__: d
 main.js:1584
defaultErrorLogger main.js:1584
ErrorHandler.handleError main.js:1644
IonicErrorHandler.handleError main.js:117966
onError.subscribe.next main.js:5278
schedulerFn main.js:4351
SafeSubscriber.__tryOrUnsub main.js:15685
SafeSubscriber.next main.js:15632
Subscriber._next main.js:15572
Subscriber.next main.js:15536
Subject.next main.js:18926
EventEmitter.emit main.js:4337
NgZone.triggerError main.js:4709
inner.inner.fork.onHandleError main.js:4670
t.handleError polyfills.js:3
r.runGuarded polyfills.js:3
(anonymous function) polyfills.js:3
n.microtaskDrainDone polyfills.js:3
o

EDIT:

Code with bug which does not execute insert queries. (addProduct methods executes on click trigger.)

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
/**
 * Generated class for the AddProductsPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-add-products',
  templateUrl: 'add-products.html',

})
export class AddProductsPage {
  productName: string;
  sqlstorage: SQLite;
  items: Array<Object>;
  db: SQLiteObject;
  mesg: string;
  constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController, public platform: Platform) {


    this.platform.ready().then(() => {
      this.sqlstorage = new SQLite();
      this.sqlstorage.create({
        name: 'data.db',
        location: 'default'
      }).then((db: SQLiteObject) => {
        this.db = db;
        console.log("Opened");

        db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
        db.executeSql("insert into product (ProductID,ProductName) values(3,'jhkj')", []);

      }).catch(e => {
        console.log(e);
      });
    });
  }
  presentToast() {
    let toast = this.toastCtrl.create({
      message: this.mesg,
      duration: 3000,
      position: 'top'
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }


   addProduct() {
        // this.sqlstorage = new SQLite();


 // this.sqlstorage.create({
    //   name: 'data.db',
    //   location: 'default'
    // }).then((db: SQLiteObject) => {
    //   console.log("Opened");
    return new Promise((resolve, reject) => {
      this.db.executeSql("insert into product (productName) values(?)", this.productName).then((data) => {
        resolve(data);
        console.log("resolve");
      }, (error) => {
        reject(error);
        console.log("reject");
      });
    });
    // this.addItem("insert into product (productName) values(?)", this.productName, db);
    // this.findAll(db);
    // }).catch(e => {
    //   console.log(e);
    // });

  }

  public createTables() {
    this.db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
  }

  public addItem(q: string, param: string, db: SQLiteObject) {
    db.executeSql(q, param).then((data) => {
      console.log("Success");
    }, (e) => {
      console.log("Error :  " + JSON.stringify(e.err));
    });
  }

  public findAll(db: SQLiteObject) {
    db.executeSql("SELECT * FROM product", []).then((data) => {
      this.items = [];
      if (data.rows.length > 0) {
        for (var i = 0; i < data.rows.length; i++) {
          this.items.push(data.rows.item(i));
          this.mesg = data.rows.item(i);
          console.log(this.mesg);
        }
      }
    }, (e) => {
      this.mesg = "Errot: " + JSON.stringify(e);
      console.log("Errot: " + JSON.stringify(e));
    });
    this.presentToast();
  }
}

1 Answer 1

1

The error occurs because you are trying to use an uninitialized SQLiteObject db. When you use the create method of SQLite, it returns a SQLiteObject which you can use to execute your SQL queries. Here is an example -

    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      console.log("Opened");          
      db.executeSql("CREATE TABLE IF NOT EXISTS product (ProductID INTEGER PRIMARY KEY AUTOINCREMENT, ProductName TEXT)", []);
    }).catch(e => {
      console.log(e);          
    });
Sign up to request clarification or add additional context in comments.

2 Comments

That really worked for given case. But I'm not able to do other operations such as insert data i have tried to pass the instance of "db: sqliteobject" and tried to used the complete code all again and changing the query "db.executeSql("insert into product (productName) values(?)", this.productName)" but I'm still getting ""Cannot call method 'executeSql' of undefined"". How could I resolve that ?
Can you post the code so that I can have a visual check of what's going wrong?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.