How to use Sqlite with ionic 2 rc.0? - sqlite

I would like to know how to use Sqlite with Ionic 2 rc.o release.I am finding it difficult as there are no examples for the latest version release and i am stuck.Nothing on the net seems to be updated.A supporting example for Sqlite would be of great use.
Thank you in advance.

1) First of all, navigate to the root folder of your project and add the plugin:
$ ionic plugin add cordova-sqlite-storage
$ npm install --save #ionic-native/sqlite
2) Create a new provider inside the project (in this example, called SqlStorage):
$ ionic g provider sqlStorage
3) I'd like to add an import to app.component.ts to initialize the plugin at startup, not mandatory:
import {SqlStorage} from '../providers/sql-storage';
...
...
constructor(public sqlStorage: SqlStorage){}
4) Add entry to app.module.ts, mandatory:
import { SQLite } from '#ionic-native/sqlite';
import { SqlStorage } from '../providers/sql-storage';
...
...
providers: [SQLite, SqlStorage]
5) Define the sql-storage.ts provider:
import { Injectable } from '#angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
#Injectable()
export class SqlStorage {
storage: any;
DB_NAME: string = '__ionicstorage';
constructor(public platform: Platform, public sqlite: SQLite) {
this.platform.ready().then(() => {
this.sqlite.create({ name: this.DB_NAME, location: 'default' })
.then((db: SQLiteObject) => {
this.storage = db;
this.tryInit();
});
});
}
tryInit() {
this.query('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)')
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
/**
* Perform an arbitrary SQL operation on the database. Use this method
* to have full control over the underlying database through SQL operations
* like SELECT, INSERT, and UPDATE.
*
* #param {string} query the query to run
* #param {array} params the additional params to use for query placeholders
* #return {Promise} that resolves or rejects with an object of the form
* { tx: Transaction, res: Result (or err)}
*/
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.storage.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
},
(err: any) => reject({ err: err }));
} catch (err) {
reject({ err: err });
}
});
}
/** GET the value in the database identified by the given key. */
get(key: string): Promise<any> {
return this.query('select key, value from kv where key = ? limit 1', [key])
.then(data => {
if (data.res.rows.length > 0) {
return data.res.rows.item(0).value;
}
});
}
/** SET the value in the database for the given key. */
set(key: string, value: string): Promise<any> {
return this.query('insert into kv(key, value) values (?, ?)', [key, value]);
}
/** REMOVE the value in the database for the given key. */
remove(key: string): Promise<any> {
return this.query('delete from kv where key = ?', [key]);
}
}
6) In your .ts page:
import {SqlStorage} from '../../providers/sql-storage';
export class ExamplePage {
constructor(public sqlStorage: SqlStorage) {
// this.sqlStorage.query(...);
// this.sqlStorage.get(key).then(data => {
// console.log(data);
// }
//...
}
}
Credit to: https://github.com/NickStemerdink with some personal changes.
Hope it will help and works fine :)
EDIT: Still works fine with Ionic v3.0.1 (2017-04-06)

in app.module.ts
import { SQLite } from '#ionic-native/sqlite';
providers: [
StatusBar,
SplashScreen,
SQLite,
{ provide: ErrorHandler, useClass: IonicErrorHandler }
]
in database provider
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
//import { Storage } from '#ionic/storage';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
import { Platform } from 'ionic-angular';
/*
Generated class for the Database provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class Database {
DB_NAME: string = 'ssddb';
constructor(public http: Http, public platform: Platform, public sqlite: SQLite) {
this.platform.ready().then(() => {
this.configureDatabase();
});
}
configureDatabase() {
this.query('CREATE TABLE IF NOT EXISTS EMP (key text primary key, value text)')
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
this.sqlite.create({
name: this.DB_NAME,
location: 'default'
})
.then((db: SQLiteObject) => {
db.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
})
})
.catch(e => console.log(e));
} catch (err) {
reject({ err: err });
}
});
}
get(key: string): Promise<any> {
return this.query('select key, value from EMP where key = ? limit 1', [key])
.then(data => {
if (data.res.rows.length > 0) {
return data.res.rows.item(0).value;
}
});
}
set(key: string, value: string): Promise<any> {
return this.query('insert into EMP(key, value) values (?, ?)', [key, value]);
}
}
in page.ts
this.database.set("333","ss");
this.database.get("333").then(data => {
console.log(data);
let toast = this.toastCtrl.create({
message: data,
duration: 10000,
position: 'bottom'
});
toast.present();
});

On ionic-storage repo they say to use Ionic Native SQLite plugin.
So like this:
import { SQLite } from 'ionic-native';
SQLite.openDatabase({
name: 'data.db',
location: 'default'
})
.then((db: SQLite) => {
db.executeSql('create table danceMoves(name VARCHAR(32))', {}).then(() => {}).catch(() => {});
})
.catch(error => console.error('Error opening database', error));

Related

Property 'catch' does not exist on type 'PromiseLike<void>

I'm getting this error in the following code. I'm using ionic3:
Property 'catch' does not exist on type 'PromiseLike
This is the link to the tutorial that I am following.
This error is showing in the VS Code.
This probably some updated syntax I'm not aware of
storetoken(t) {
this.afd.list(this.firestore).push({
uid: firebase.auth().currentUser.uid,
devtoken: t
}).then(() => {
alert('Token stored');
})
.catch(() => {
alert('Token not stored');
})
this.afd.list(this.firemsg).push({
sendername: 'vivek',
message: 'hello'
}).then(() => {
alert('Message stored');
})
.catch(() => {
alert('Message not stored');
})
}
**This is the entire code for the home.ts file which sends token onto firebase database:Please refer this as well, as i'm also getting another error:Error: Uncaught (in promise): Error: StaticInjectorError[AngularFireDatabase] when I remove the catch block. **
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { AngularFireDatabase } from 'angularfire2/database';
import firebase from 'firebase';
import { HttpClientModule } from '#angular/common/http';
import { HttpModule } from '#angular/http';
declare var FCMPlugin;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
firestore = firebase.database().ref('/pushtokens');
firemsg = firebase.database().ref('/messages');
constructor(public navCtrl: NavController, public afd:
AngularFireDatabase) {
this.tokensetup().then((token) => {
this.storetoken(token);
})
}
ionViewDidLoad() {
FCMPlugin.onNotification(function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
alert( JSON.stringify(data) );
}else{
//Notification was received in foreground. Maybe the user needs to be
notified.
alert( JSON.stringify(data) );
}
});
FCMPlugin.onTokenRefresh(function(token){
alert( token );
});
}
tokensetup() {
var promise = new Promise((resolve, reject) => {
FCMPlugin.getToken(function(token){
resolve(token);
}, (err) => {
reject(err);
});
})
return promise;
}
storetoken(t) {
this.afd.list(this.firestore).push({
uid: firebase.auth().currentUser.uid,
devtoken: t
}).then(() => {
alert('Token stored');
}).catch(() => {
alert('Token not stored');
})
this.afd.list(this.firemsg).push({
sendername: 'vivek',
message: 'hello'
}).then(() => {
alert('Message stored');
}).catch(() => {
alert('Message not stored');
})
}
}
push returns a ThenableReference and not a Promise.
Combined Promise and Reference; resolves when write is complete, but can be used immediately as the Reference to the child location.
It means you can use it as a future reference to the written data.
See also in codebase.
ThenableReference Def here.
export interface ThenableReference extends Reference, PromiseLike<Reference> {}
Or you can do the recommended way i.e:
You cannot use catch currently.
this.afd.list(this.firestore).push({ uid: firebase.auth().currentUser.uid, devtoken: t });
Note: There is an open issue here if you want to follow it.

SQLite in Ionic 3 getting data null after navigate to another page

Please help me. I've made Database Provider to connect with SQLite in ionic 3. When i want to get the data rows it's always getting null but when I check data length it has 1
This is my DatabaseProvider
import { Injectable } from '#angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Storage } from '#ionic/storage';
#Injectable()
export class DatabaseProvider {
private db: SQLiteObject;
private databaseReady: BehaviorSubject<boolean>;
constructor(private storage: Storage, private sqlite: SQLite, private platform: Platform) {
this.databaseReady = new BehaviorSubject(false);
this.platform.ready().then(() => {
this.sqlite.create({
name: 'takia.db',
location: 'default'
}).then((database: SQLiteObject) => {
this.db = database;
this.storage.get('database_filled').then(val => {
if (val) {
this.databaseReady.next(true);
} else {
this.initDB();
}
});
}).catch(e => { console.log(e); });
});
}
initDB(){
this.db.executeSql('CREATE TABLE IF NOT EXISTS users(user_id INTEGER PRIMARY KEY, username TEXT, email TEXT, password TEXT)', {})
.then(res => {
this.db.executeSql('INSERT INTO users VALUES(NULL,?,?,?,?)',['admin','admin.#email.com','password'])
.then(res => {
this.databaseReady.next(true);
this.storage.set('database_filled', true);
}).catch(e => {
console.log(e);
});
}).catch(e => {
console.log(e)
});
this.db.executeSql('CREATE TABLE IF NOT EXISTS questions(user_id INTEGER PRIMARY KEY, username TEXT, email TEXT, password TEXT)', {})
.then(res => {
this.db.executeSql('INSERT INTO users VALUES(NULL,?,?,?,?)',['admin','admin.tazkiaiibs.sch.id','bismillah'])
.then(res => {
this.databaseReady.next(true);
this.storage.set('database_filled', true);
}).catch(e => {
console.log(e);
});
}).catch(e => {
console.log(e)
});
}
getUser(){
return this.db.executeSql('SELECT user_id, username, email, password, COUNT(*) total FROM users', [])
.then(res => {
let users = [];
if (res.rows.length > 0) {
for (var i = 0; i < res.rows.length; i++) {
let row = res.rows.item(i);
users.push(row);
}
}
return users;
}, err => {
console.log('Error: ', err);
return [];
});
}
getDatabaseState() {
return this.databaseReady.asObservable();
}
}
and this is my code in component
constructor(public navCtrl: NavController,
public navParams: NavParams,
private dbProvider: DatabaseProvider,
private toastCtrl: ToastController) {
this.loadData();
}
loadData(){
this.dbProvider.getUser().then(data=>{
if(data.length>0){
this.id = data[0].id;
this.old_password = data[0].password;
this.username = data[0].username;
this.email = data[0].email;
let toast = this.toastCtrl.create({
message: 'ID '+data[0].username,
duration: 3000
});
toast.present();
}else{
let toast = this.toastCtrl.create({
message: 'No data'+data.length,
duration: 3000
});
toast.present();
}
});
}
When i run loadData function the length is not 0 but the data is null.
The comment under the question seemed to help, so I form it as an answer to hopefully collect some reputation points.
The problem seems to be a misformed SQL-query. The count(*) part makes the query return at least one row. Therefore the other fields might be NULL, when queried before data is added to the database.
The function "getUser" is called before the promise callback is executed.

SQLiteObject is undefined in ionic 3

I'm using ionic-native SQLite database for Ionic application and for testing in browser i'm using WebSQL.
It's all working fine in browser, but when running application in android devices. it gives me error like Cannot read property 'transaction' of undefined.
Below is code for reference.
1) DBProvider.ts
import { Platform } from 'ionic-angular';
import { Injectable } from '#angular/core';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
declare var window: any;
#Injectable()
export class DBProvider {
DB_NAME: string = 'DailySheet.db';
public websql = null;
public sqlite: SQLite;
sqliteobj: any;
public AppUsers = [];
constructor(public platform: Platform) {
if (this.platform.is('core')) {
this.websql = window.openDatabase(this.DB_NAME, "1.0", "Test DB", 2 * 1024 * 1024);
console.log('Database opened.');
this.createTable();
}
this.platform.ready().then(() => {
if (!this.platform.is('core')) {
this.sqlite.create({ name: this.DB_NAME, location: 'default' })
.then((db: SQLiteObject) => {
console.log('Database opened.');
this.sqliteobj = db;
this.createTable();
});
}
});
}
createTable() {
this.query(`CREATE TABLE IF NOT EXISTS AppUser (
UserId INTEGER NOT NULL,
MobileNo TEXT NOT NULL UNIQUE,
Email TEXT,
PRIMARY KEY(UserId)
)`)
.then(data => {
console.log('Table created.');
})
.catch(err => {
console.error('Unable to create initial storage tables', err.tx, err.err);
});
}
getAppUsers(): Promise<any> {
let query = 'SELECT * FROM AppUser';
return this.query(query)
.then(data => {
if (data.res.rows.length > 0) {
console.log('Rows found.');
return data.res.rows;
}
else {
console.log('No rows found.');
}
});
}
insertAppUser(): Promise<any> {
let id = 1;
let mobileno = '8905606191';
let email = 'niravparsana94#gmail.com';
return this.query('INSERT INTO AppUser (UserId, MobileNo, Email) VALUES (' + id + ' ,\"' + mobileno + '\" ,\"' + email + '\")')
.then(data => {
console.log('Insert success.');
return data;
})
.catch(err => {
console.error('Unable to insert', err.tx, err.err);
});
}
updateAppUser(UserId): Promise<any> {
let query = "UPDATE Todo SET Email=? WHERE UserId=?";
return this.query(query, ['niravparsana#outlook.com', UserId])
.then(data => {
console.log('AppUser Updated.');
return data;
})
.catch(err => {
console.error('Unable to update', err.tx, err.err);
});
}
deleteAppUser(UserId): Promise<any> {
let query = "DELETE FROM AppUser WHERE UserId=?";
return this.query(query, [UserId])
.then(data => {
return data;
})
.catch(err => {
console.error('Unable to delete', err.tx, err.err);
});
}
query(query: string, params: any[] = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
if (this.platform.is('core')) {
this.websql.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
},
(err: any) => reject({ err: err }));
}
else {
this.sqliteobj.transaction((tx: any) => {
tx.executeSql(query, params,
(tx: any, res: any) => resolve({ tx: tx, res: res }),
(tx: any, err: any) => reject({ tx: tx, err: err }));
},
(err: any) => reject({ err: err }));
}
} catch (err) {
reject({ err: err });
}
});
}
}
2) home.ts
import { Component, OnInit } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
import { DBProvider } from '../../providers/DBProvider';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage implements OnInit {
AppUsers: Array<Object>;
constructor(public navCtrl: NavController, private platform: Platform, public db: DBProvider) {
}
ionViewDidLoad() {
this.deleteAppUser();
this.insertAppUser();
this.getAllAppUsers();
}
ngOnInit() {
}
public deleteAppUser() {
this.db.deleteAppUser(1)
.then(data => {
if (data.res.rowsAffected == 1) {
console.log('AppUser Deleted.');
}
else {
console.log('No AppUser Deleted.');
}
})
.catch(ex => {
console.log(ex);
});
}
public insertAppUser() {
this.db.insertAppUser()
.then(data => {
})
.catch(ex => {
console.log(ex);
});
}
public getAllAppUsers() {
this.db.getAppUsers()
.then(data => {
this.AppUsers = data;
})
.catch(ex => {
console.log(ex);
});
}
}
While debugging, I figured out somewhat that code runs in difference sequence in browser and mobile.
In browser
DBProvider constructor
this.CreateTable() function(DBProvider.ts)
this.deleteAppUser() function(home.ts)
this.insertAppUser() function(home.ts)
this.getAllAppUsers() function(home.ts)
In Android device
DBProvider constructor
this.deleteAppUser() function(home.ts)
this.insertAppUser() function(home.ts)
this.getAllAppUsers() function(home.ts)
this.CreateTable() function(DBProvider.ts)
As you can this.sqliteobj is assigned in DBProvider constructor. but while debug i found that funtions from home.ts are calling before this.sqliteobj get assigned, that's why it gives an error like Cannot read property 'transaction' of undefined. But then question is why functions from home.ts getting called before this.sqliteobj get assigned?
To my knowledge you need this.sqlite.create(... in every call on the sqlite database. So you have to include it in your query function before the sqliteobj.

Ionic 2: Unable to create table TypeError: Cannot read property 'apply' of undefined

I am trying to open a database and create a table in my Ionic 2 app.
The following method is part of a service and is supposed to open the db and create the table:
initDb() {
let db = new SQLite();
db.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
db.executeSql("CREATE TABLE IF NOT EXISTS people (avatarUrl VARCHAR, firstName VARCHAR, lastName VARCHAR)", []).then((data) => {
console.log("Table created: ", data);
}, (error) => {
console.error("Unable to create table", error);
})
}, (error) => {
console.error("Unable to open database", error);
});
}
The method is called in my home page's constructor:
constructor(public platform: Platform, public navCtrl: NavController, public dbService: DBService) {
this.platform.ready().then(() => {
this.dbService.initDb();
});
}
I have no idea why I am getting this error (refer to the title).
Thanks
Sorry, I could not reproduce this error but build a testapp on my own. This app works with me, despite this is called within ready as well:
app.component.ts:
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen, SQLite } from 'ionic-native';
import { TabsPage } from '../pages/tabs/tabs';
import { DbService } from '../providers/db-service';
#Component({
templateUrl: 'app.html',
providers: [DbService]
})
export class MyApp {
rootPage = TabsPage;
constructor(public platform: Platform, public dbService: DbService) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
this.dbService.initDb();
});
}
}
I made this service by using this ionic-command:
ionic g provider DbService
db-service.ts:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { SQLite } from 'ionic-native';
/*
Generated class for the DbService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class DbService {
constructor(public http: Http) {
console.log('Hello DbService Provider');
}
initDb() {
let db = new SQLite();
db.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
db.executeSql("CREATE TABLE IF NOT EXISTS people (avatarUrl VARCHAR, firstName VARCHAR, lastName VARCHAR)", []).then((data) => {
console.log("Table created: ", data);
}, (error) => {
console.error("Unable to create table", error);
})
}, (error) => {
console.error("Unable to open database", error);
});
}
}
ionic-version: 2.1.18
cordova-version 6.0.0
Hope it helps.

ionic 2 sqlite run on android : cannot read property executeSql of undefined

I write a test tabs ionic 2 app use sqlite plugin. I wrapper the sqlite as provier:
import { SQLite, Device } from 'ionic-native';
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the SqliteHelper provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class SqliteHelper {
public db : SQLite;
public log : string = "";
constructor(public http: Http) {
console.log('Hello SqliteHelper Provider');
}
public initDb() {
this.db = new SQLite();
this.log += "openDatabase。。。";
// if (Device.device.platform)
this.db.openDatabase({
name: "data.db",
location: "default"
}).then((data) =>{
this.log += ("open ok " + JSON.stringify(data));
}, (err) => {
this.log += ("open err " + err.message + " " + JSON.stringify(err));
});
}
public executeSql(statement: string, parms:any) {
return this.db.executeSql(statement, parms);
}
}
And init sqlitehelper in app.components :
constructor(platform: Platform, sqliteHelper : SqliteHelper, events: Events) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
sqliteHelper.initDb();
events.publish("sqlite:inited", null);
StatusBar.styleDefault();
Splashscreen.hide();
});
}
And I load data from the first tabs page in constructor with platform.ready, run it on android will cause err: cannot read property executeSql of undefined.
If I load data from a button click, it's ok. or I put the loaddata to the second page's constructor, it's ok too.why?who can help me , I want to put code to the first page and load data at page started.
I had the same error when i try to insert in database for that reason i added "executeSql" function inside transaction:
this.database.openDatabase({
name: "sis.db",
location: "default"
}).then(() => {
this.database.executeSql("CREATE TABLE IF NOT EXISTS profile(id integer primary key autoincrement NOT NULL ,name Text NOT NULL)", []).then((data) => { console.log('profile table created'); }, (error) => { console.log('Unable to create table profile'); })
this.database.transaction(tr => { tr.executeSql("insert into profile(id,name) values(12,'Ibrahim')", []); }).then(d => { console.log('Data inserted ya hima'); }, err => { console.error('unable to insert data into profile table'); });
this.database.executeSql("select id from profile", []).then(d => { console.log('inserted id=' + d.rows.item(0).app_id); }, err => { console.error('unable to get ID from profile table'); });
}, (error) => {console.error(error); }
);

Resources