Jedna od najvažnijih funkcionalnosti svake mobilne aplikacije je mogućnost trajnog spremanja podataka kako bi se oni mogli koristiti kasnije. Podaci koje spremite u SQLite bazu podataka mogu se koristiti kada npr. aplikacija nije povezana s mrežom, a želite korisniku omogućiti da i dalje može pregledavati sadržaj mobilne aplikacije.
VAŽNA NAPOMENA! – Testiranje SQLite baze ne možete raditi unutar web preglednika nego isključivo na uređaju.
Instalacija plugina
Ionic Native 3.x
Ako koristite Ionic Native 3.x plugin ćete instalirati naredbama
1 2 |
$ npm install --save @ionic-native/sqlite $ ionic plugin add cordova-sqlite-storage |
U ovom slučaju, kada koristite novi Ionic Native 3.x, plugin se poziva na sljedeći način
1 |
import { SQLite } from '@ionic-native/sqlite'; |
Umjesto kao što je bilo do sada
1 |
import { SQLite } from 'ionic-native'; |
Korištenje SQLite plugina
Plugin za početak trebamo dodati u app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { SQLite } from '@ionic-native/sqlite'; @NgModule({ declarations: [ MyApp, HomePage ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, SQLite, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {} |
Kreiranje tablica
Sada se fokusiramo na app.component.ts gdje ćemo kreirati sve potrebne tablice. Svaki put kada se aplikacija pokrene ova će root komponenta kreirati potrebne tablice ako one već ne postoje.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { SQLite, SQLiteObject } from '@ionic-native/sqlite'; import { HomePage } from '../pages/home/home'; @Component({ templateUrl: 'app.html', providers: [SQLite] }) export class MyApp { rootPage:any = HomePage; constructor(_platform: Platform, _statusBar: StatusBar, _splashScreen: SplashScreen, private _sqlite: SQLite) { _platform.ready().then(() => { //SQLite početak this._sqlite.create({ name: 'baza.db', location: 'default' }) .then((db: SQLiteObject) => { db.executeSql("CREATE TABLE IF NOT EXISTS mojaTablice (mojatablicaId INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, user_name TEXT, location TEXT)", {}) .then(() => console.log('Executed SQL')) .catch(e => console.log(e)); db.executeSql("CREATE TABLE IF NOT EXISTS mojaDrugaTablice (mojadrugatablicaId INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)", {}) .then(() => console.log('Executed SQL')) .catch(e => console.log(e)); }) .catch(e => console.log(e)); //SQLite kraj _statusBar.styleDefault(); _splashScreen.hide(); }); } } |
Korištenje SQLite baze
Na sljedeći način koristimo ranije kreirane tablice. Prvo u konstruktoru moramo otvoriti SQLite bazu. Nakon toga možemo unositi podatke u SQLite bazu, čitati spremljene podatke iz nje ili ih obrisati.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
import { Component } from '@angular/core'; import { NavController, Platform } from 'ionic-angular'; import { ApiProvider } from '../../providers/api-providers'; import { SQLite, SQLiteObject } from '@ionic-native/sqlite'; @Component({ selector: 'page-home', templateUrl: 'home.html', providers: [SQLite] }) export class HomePage { public MyDataList: Array<Object>; constructor(public _navCtrl: NavController, public _platform: Platform, public _api: ApiProvider, private _sqlite: SQLite) { //Inicijalizacija SQLite baze this._platform.ready().then(() => { this._sqlite = new SQLite(); this._sqlite.openDatabase({name: "baza.db", location: "default"}).then(() => { }, (error) => { console.log("Greška baze: ", error); }); }); } //Dohvati podatke s API-ja i spremi ih u SQLite bazu saveToSqlite(){ //pozivanje API-ja this._api.getMyData().subscribe(res => { //Spremi podatke u lokalnu SQLite bazu if(res.length > 0) { for(var i = 0; i < res.length; i++) { // console.log(res[i].from); this._database.executeSql("INSERT INTO mojaDrugaTablice (firstname, lastname, date) VALUES (?,?)", [res[i].firstname, res[i].lastname]).then((data) => { console.log("Spremljeno: " + JSON.stringify(data)); }, (error) => { console.log("Greška: " + JSON.stringify(error.err)); }); } } }); } //Dohvaćanje lokalnu baze getMyOfflineData(){ this._database.executeSql("SELECT * FROM mojaDrugaTablice", []).then((data) => { this.MyDataList = []; if(data.rows.length > 0) { for(var i = 0; i < data.rows.length; i++) { this.MyDataList.push({ mojadrugatablicaId: data.rows.item(i).mojadrugatablicaId, firstname: data.rows.item(i).firstname, lastname: data.rows.item(i).lastname }); } } }, (error) => { console.log("Greška kod dohvaćanja offline baze: " + JSON.stringify(error)); }); } //Isprazni lokalnu bazu deleteMyOfflineData() { this._database.executeSql("DELETE FROM mojaDrugaTablice", []).then((data) => { console.log('mojaDrugaTablica SQLite deleted!'); }, (error) => { console.log("Greška kod brisanja: " + JSON.stringify(error.err)); }); } ionViewWillEnter(){ //Spremi u SQLite this.saveToSqlite(); //Dohvati iz SQLite this.getMyOfflineData(); //Isprazni SQLite this.deleteMyOfflineData(); } } |
Spremljene podatke možemo prikazati na sljedeći način
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<ion-header> <ion-navbar> <ion-title> Ionic 2 - SQLite </ion-title> <button (click)="saveToSqlite()">Save Offline Data</button> <button (click)="getMyOfflineData()">Get Offline Data</button> <button (click)="deleteMyOfflineData()">Delete Offline Data</button> </ion-navbar> </ion-header> <ion-content padding> <ion-list> <ion-item *ngFor="let data of MyDataList"> {{MyDataList.firstname}} {{MyDataList.lastname}} </ion-item> </ion-list> </ion-content> |
Zaključak
Ovo je najjednostavniji prikaz korištenja SQLite baze podataka unutar Ionic 2 projekta. U jednom od sljedećih blog postova pokazati ću kako napraviti SQLite servis koji će olakšati upravljanje offline podacima tj. u kojem će se odvijati sva logika vezana uz kreiranje tablica, spremanje, čitajne i brisanje podataka.
You can send me a link? In blog, the link “Read more” not work
All links should work now. Thank you for mentioning that.
Hey man, nice job. Your blog is very good.
What can you tell me about that: ApiProvider file?
import { ApiProvider } from ‘../../providers/api-providers’;
Could you show me the code?
And I’m having problems with SQLite too, it seems that the: “openDatabase” (this._sqlite.openDatabase(…)) method no longer exist.
Hi Marcus,
Thanks for your comment.
You can see more advanced and better version of this blog post at https://www.tomislavstankovic.com/blog/ionic-2-3-sqlite-servis/.
Yes, in the meantime some methods have changed. For example
this._sqlite.openDatabase
is nowthis._sqlite.create
More about content of ApiProvider you can find at https://www.tomislavstankovic.com/blog/ionic2-prikaz-json-podatak-api/
Content of ApiProvider:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiProvider {
constructor(public _http: Http) {
//console.log('Hello ApiProvider');
}
getMyData(){
return this._http.get('https://randomuser.me/api/?results=10')
.map(res => res.json());
}