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

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.

Related

Sending data to an imported module in React Native

I have a module called Chat.js that imports Fire.js in order to send data (message comes into Chat.js, and Fire.js handles storage).
I have a recipient's user ID that is only currently available in Chat.js, but it is important to get to Fire.js in order to store appropriately.
I removed some info for brevity, this is my current Chat.js:
import Fire from './Fire';
class Chat extends React.Component<Props> {
state = {
messages: [],
};
get user() {
return {
name: this.props.navigation.state.params.name,
_id: Fire.shared.uid,
};
}
render() {
return (
<GiftedChat
messages={this.state.messages}
onSend={Fire.shared.send}
user={this.user}
/>
);
}
componentDidMount() {
Fire.shared.on(message =>
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, message),
}))
);
}
componentWillUnmount() {
Fire.shared.off();
}
}
export default Chat;
And this is my current Fire.js:
import firebase from 'react-native-firebase';
class Fire {
constructor() {
}
get ref() {
var recipient = 'recipientId'
return firebase.database().ref('messages/' + this.uid + '/' + recipient);
}
parse = snapshot => {
const { timestamp: numberStamp, text, user } = snapshot.val();
const { key: _id } = snapshot;
const timestamp = new Date(numberStamp);
const message = {
_id,
timestamp,
text,
user,
};
return message;
};
on = callback =>
this.ref
.limitToLast(20)
.on('child_added', snapshot => callback(this.parse(snapshot)));
// send the message to the Backend
send = messages => {
for (let i = 0; i < messages.length; i++) {
const { text, user } = messages[i];
const message = {
text,
user,
timestamp: this.timestamp,
};
this.append(message);
}
};
append = message => this.ref.push(message);
// close the connection to the Backend
off() {
this.ref.off();
}
}
Fire.shared = new Fire();
export default Fire;
I currently need to get the recipient ID, which is available in chat.js under
this.props.navigation.state.params.uid
Into the Fire.js lines:
get ref()
{
var recipient = 'recipientId'
I can't seem to get this uid into get ref()
Use getter and setters in Fire.js.
In Fire.js
setRecipient (id){
this.recipientId = id;
}
get getRecipientId () {
return this.recipientId;
}
And then call Fire.setRecipient(yourId) in Chat.js.

Expected Argument Error for .doc() when called on Firestore Collection

I want to create a new user document in my Cloud Firestore database whenever a new user logs in. Each doc should have a unique id and I want a "uid" property for each user to match the unique auto-generated id for the doc. At first, I just always ran an update on the user, but I figured it could be helpful to separate my create and update logic. As you can see I haven't worked out how to query if a user exists, but I figured I should test the createUser function before continuing.
Anyway, while I was testing my createUser function I ran into a compilation error.
ERROR in src/app/services/auth.service.ts(64,22): error TS2554:
Expected 1 arguments, but got 0.
UPDATE:
When I try to run the function from localhost after compilation I get this error in the console.
Function CollectionReference.doc() requires its first argument to be
of type string, but it was: undefined
Here is my proposed solution:
import { Injectable } from '#angular/core';
import { User } from './../models/user.model';
import { PermissionsService } from './permissions.service';
import { auth } from 'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import {
AngularFirestore,
AngularFirestoreDocument,
AngularFirestoreCollection,
} from 'angularfire2/firestore';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
#Injectable({
providedIn: 'root',
})
export class AuthService {
usersCollection: AngularFirestoreCollection<User> = null;
user: Observable<User>;
constructor(
private afAuth: AngularFireAuth,
private db: AngularFirestore,
private permissionsService: PermissionsService,
) {
this.usersCollection = db.collection('users');
this.user = this.afAuth.authState.pipe(
switchMap((user) => {
if (user) {
return this.db
.doc<User>(`users/${user.uid}`)
.valueChanges();
} else {
return of(null);
}
}),
);
}
loginGoogle() {
const provider = new auth.GoogleAuthProvider();
return this.oAuthLogin(provider);
}
loginFacebook() {
const provider = new auth.FacebookAuthProvider();
return this.oAuthLogin(provider);
}
loginTwitter() {
const provider = new auth.TwitterAuthProvider();
return this.oAuthLogin(provider);
}
oAuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider).then((credential) => {
//if(the user exists already)
//this.updateUserData(credential.user);
//else
this.createUser();
});
}
createUser() {
const newUserRef = this.usersCollection.doc<User>(); // Error here
let newUser: User;
this.user.subscribe((userData) => {
newUser = {
uid: newUserRef.id,
email: userData.email,
photoURL: userData.photoURL,
displayName: userData.displayName,
roles: {
member: true,
},
permissions: this.permissionsService.memberPermissions;
};
});
newUserRef
.set(newUser)
.then(() => {
console.log('created user');
})
.catch((err) => {
console.log('Error adding user: ' + err);
});
}
updateUserData(user) {
const userRef: AngularFirestoreDocument<any> = this.db.doc(
`users/${user.uid}`,
);
const userPermissions = this.addPermissions(userRef);
console.log(userPermissions); // This works
const data: User = {
uid: user.uid,
email: user.email,
photoURL: user.photoURL,
displayName: user.displayName,
roles: {
member: true,
}, // I need to make sure this keeps current user roles
permissions: userPermissions,
};
console.log(data); // This works
userRef
.set(data)
.then(() => {
console.log('Success: Data for userDoc overwritten');
})
.catch((err) => {
console.error('Error writing to userDoc: ' + err);
});
}
addPermissions(userRef) {
const tempPermissions = [];
userRef.valueChanges().subscribe((userdata) => {
if (userdata.roles.reader === true) {
tempPermissions.push(this.permissionsService.memberPermissions);
}
if (userdata.roles.author === true) {
tempPermissions.push(this.permissionsService.authorPermissions);
}
if (userdata.roles.admin === true) {
tempPermissions.push(this.permissionsService.adminPermissions);
}
});
return tempPermissions;
}
checkPermissions(permission: string) {
if (!this.user) {
return false;
} else {
this.user.subscribe((data) => {
for (const p of data.permissions) {
if (p === permission) {
return true;
}
}
return false;
});
}
}
logout() {
this.afAuth.auth.signOut();
this.user = null;
}
}
I checked the documentation on the .doc() function and it should work fine with 0 arguments. It should be returning an empty doc reference. However, it keeps throwing the error saying it expects 1 argument. Any idea why this isn't working?

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.

How can I use Ionic 2 Pulling Refresher in my app?

Hi all I'M working on angularjs 2/ionic2 mobile app , i need to do pulling refresher in my app, we have tried this link:- https://ionicframework.com/docs/v2/api/components/refresher/Refresher/ process i got refreshing the page but it's not get dismissLoader, we have given the images of my app refreshing:-
we don't know where we did the mistake and where we need to add the correct functionality in my project...
while we pulling the page it's refreshing but it's not get dismiss, Refreshing text and icon showing it's not get dismissed...
what we expecting once we pulled the page it's need to refresh after that refreshing text and icon need to be dismiss...
**we added coding only in html:-****
<ion-refresher (ionRefresh)="setFilteredItems($event)">
<ion-refresher-content refreshingSpinner="circles" refreshingText="Refreshing...">
</ion-refresher-content>
</ion-refresher>
we have not added anything in type script part...so please check and update the solution please....
we have created example Plunker
please update the plunker as well to know the solution, thanks.....
My Type Script constructor code:-
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { GlobalStateService } from '../../services/global-state.service';
import { AccountSigninPage } from '../account-signin/account-signin';
import { AccountSignupPage } from '../account-signup/account-signup';
import { ActivityAddPage } from '../activity-add/activity-add';
import { Activity } from "../../services/actopi-sdk/model/Activity";
import { UserLoginService } from "../../services/account-management.service";
import { ResourceListPage } from '../resource-list/resource-list';
import { IamAuthorizerClient } from "../../services/actopi-api.service";
import { CustomAuthorizerClient, NoAuthorizationClient, UserPoolsAuthorizerClient } from "../../services/actopi-api.service";
import { Config } from '../../config/config'
import { Logger } from '../../services/logger.service';
import 'rxjs/add/operator/debounceTime';
import { FormControl } from '#angular/forms';
declare const AWS: any;
#Component({
templateUrl: 'activity-list.html',
})
export class ActivityListPage {
initialized = false;
accountSigninPage = AccountSigninPage;
accountSignupPage = AccountSignupPage;
activityAddPage = ActivityAddPage;
activitys: Activity[] = [];
resourceListPage = ResourceListPage;
searchTerm: string = '';
searchControl: FormControl;
displayDeleteActivityConfirmation(activityId, activityName) {
console.log("Deleting activityID " + activityId);
let confirm = this.globals.getAlertController().create({
title: 'Delete activity?',
message: `Are you sure you want to delete [<b>${activityName}</b>]? All resources and bookings associated with [<b>${activityName}</b>] will also be deleted!`,
buttons: [
{
text: 'Cancel',
handler: () => { /* do nothing */ }
},
{
text: 'OK',
handler: () => {
this.deleteActivity(activityId)
.then(() => {
this.globals.dismissLoader();
this.globals.displayToast(`Activity [${activityName}] has been successfully deleted`);
})
.catch((err) => {
this.globals.dismissLoader();
this.globals.displayAlert('Error encountered',
'Delete failed. Please check the console logs for more information.');
console.log(err);
});
}
}
]
});
confirm.present();
}
deleteActivity(activityId): Promise<void> {
return new Promise<void>((resolve, reject) => {
// delete from the database
this.globals.displayLoader("Deleting...");
this.customAuthClient.getClient().activitysDelete(activityId).subscribe(
() => {
// remove the item from the activitys array
let index = this.activitys.findIndex(activity => { return activity.activityId == activityId });
if (index > -1) {
this.activitys.splice(index, 1);
}
resolve();
},
(err) => {
reject(err);
}
);
});
}
gotoResourceListPage(activity) {
this.navCtrl.push(ResourceListPage, activity);
}
filterItems(searchTerm): void {
this.activitys = [];
this.userPoolsAuthClient.getClient().activitysList().subscribe(
(data) => {
this.activitys = data.items.filter((activity) => {
return activity.name.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1;
});
this.globals.dismissLoader();
this.initialized = true;
},
(err) => {
this.globals.dismissLoader();
this.initialized = true;
console.error(err);
this.globals.displayAlert('Error encountered',
`An error occurred when trying to load the activitys. Please check the console logs for more information.`)
});
}
loadActivitysWithAuth(): void {
this.activitys = [];
this.userPoolsAuthClient.getClient().activitysList().subscribe(
(data) => {
// this.activitys = data.items
// sort by name
let searchTerm: string = '';
// this.activitys = data.items.sort((a, b) => {
// return a.name.localeCompare(b.name);
// });
this.globals.dismissLoader();
this.initialized = true;
},
(err) => {
this.globals.dismissLoader();
this.initialized = true;
console.error(err);
this.globals.displayAlert('Error encountered',
`An error occurred when trying to load the activitys. Please check the console logs for more information.`)
}
);
};
loadActivitysWithoutAuth(): void {
this.activitys = [];
this.noAuthClient.getClient().activitysList().subscribe(
(data) => {
// this.activitys = data.items
// sort by name
this.activitys = data.items.sort((a, b) => {
return a.name.localeCompare(b.name);
});
this.globals.dismissLoader();
this.initialized = true;
},
(err) => {
this.globals.dismissLoader();
this.initialized = true;
console.error(err);
this.globals.displayAlert('Error encountered',
`An error occurred when trying to load the activitys. Please check the console logs for more information.`)
}
);
};
constructor(private navCtrl: NavController, public globals: GlobalStateService, private noAuthClient: NoAuthorizationClient, private customAuthClient: CustomAuthorizerClient, private userPoolsAuthClient: UserPoolsAuthorizerClient, private authClient: IamAuthorizerClient) {
this.searchControl = new FormControl();
}
ionViewDidEnter() {
Logger.banner("Activitys");
this.activitys = [];
if (!this.initialized) {
this.initialized = false;
if (UserLoginService.getAwsAccessKey() != null) {
// if (CognitoUtil.getUserState() === UserState.SignedIn) {
// console.log(AWS.config.credentials);
UserLoginService.getAwsCredentials()
.then((data) => {
this.globals.displayLoader("Loading...");
this.setFilteredItems(refresher);
this.searchControl.valueChanges.debounceTime(700).subscribe(search => {
this.globals.displayLoader("Loading...");
this.setFilteredItems(refresher);
this.globals.dismissLoader();
});
})
.catch((err) => {
console.log("ERROR: Unable to load activitys!");
console.log(err)
})
}
}
}
setFilteredItems(refresher) {
return this.filterItems(this.searchTerm);
refresher.complete();
}
}
You need to call refresher.complete() to dismiss your refresher once loading of new data is done..
setFilteredItems(refresher?:any){
//async call to load.
// in the then function
if(refresher)
refresher.complete();
}
}
The refresher is sent from the html onRefresh. With ? you can call without passing object in your code.
this.setFilteredItems();
Also consider refactoring your code. You should ideally call complete after async task ia done and no point in returning another function to the html side and calling complete after return will just end up as dead code.

How to use Sqlite with ionic 2 rc.0?

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));

Resources