Ionic 2 i SQLite

Ionic 2 – SQLite za trajno spremanje podataka

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

$ 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

import { SQLite } from '@ionic-native/sqlite';

Umjesto kao što je bilo do sada

import { SQLite } from 'ionic-native';

Korištenje SQLite plugina

Plugin za početak trebamo dodati u app.module.ts

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.

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.

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

<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.

Objavio

Tomislav Stanković

Bloger širokog raspona interesa od kojih dio voli objaviti na ovom blogu. U neslobodno vrijeme Angular developer mobilnih i web aplikacija.

4 misli o “Ionic 2 – SQLite za trajno spremanje podataka”

  1. 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.

    1. 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 now this._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());
      }

Odgovori

Vaša adresa e-pošte neće biti objavljena. Obavezna polja su označena sa *