Membuat Aplikasi Reminder Ionic 3 SQLite dan Local Notifications - Mari Belajar Coding

14 Juni 2019

Membuat Aplikasi Reminder Ionic 3 SQLite dan Local Notifications


Membuat Aplikasi Reminder Ionic 3 SQLite dan Local Notifications

Selamat datang di blog mari belajar coding. Pada tutorial kali ini kita akan belajar membuat sebuah aplikasi mobile sederhana menggunakan framework Ionic 3 sqlite dan plugin local notifications, yaitu aplikasi reminder atau pengingat. Aplikasi ini akan memunculkan notifikasi sesuai jadwal  yang telah di tentukan oleh pengguna.

Disini saya menggunakan ionic versi 3, untuk lebih jelasnya lihat gambar dibawah ini.
Membuat Aplikasi Reminder Ionic 3 SQLite dan Local Notifications
Membuat Aplikasi Reminder Ionic 3 SQLite dan Local Notifications
Pertama-tama create app baru menggunakan ionic 3 dengan nama aplikasi reminder menggunakan cmd atau terminal dengan mengetikkan kode di bawah ini.
ionic start reminder blank
Instal plugin sqlite dan local notifications. Plugin sqlite digunakan untuk membuat database sebagai tempat menyimpan data reminder. Plugin local notifications digunakan untuk membuat sebuah notifikasi.
ionic cordova plugin add cordova-sqlite-storage --save
npm install @ionic-native/sqlite@4 --save

ionic cordova plugin add cordova-plugin-local-notification
npm install --save @ionic-native/local-notifications@4

Buat sebuah provider bernama database.
ionic generate provider database
Buat dua halaman untuk input data reminder dan edit data reminder.

ionic generate page input-data
 
ionic generate page edit-data
Tambahkan module httpmodule, sqlite, local notifications, provider database, halaman input dan edit data pada file app.module.ts yang berada pada src/app/app.module.ts. Lihat baris yang di beri highlight.
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { InputDataPage } from '../pages/input-data/input-data';
import { EditDataPage } from '../pages/edit-data/edit-data';

import { HttpModule } from '@angular/http';
import { SQLite } from '@ionic-native/sqlite';
import { LocalNotifications } from '@ionic-native/local-notifications/';
import { DatabaseProvider } from '../providers/database/database';
 
@NgModule({
  declarations: [
    MyApp,
    HomePage,
    InputDataPage,
    EditDataPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    InputDataPage,
    EditDataPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    SQLite,
    LocalNotifications,
    DatabaseProvider,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
    
  ]
})
export class AppModule {}
Selanjutnya kita akan membuat sebuah fungsi crud(create, read, update, delete) data reminder pada halaman database.ts yang berada pada src/providers/database.ts. Kode lengkap databse.ts seperti dibawah ini, setiap fungsi sudah di beri keterangan.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
/*
  Generated class for the DatabaseProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class DatabaseProvider {

  private db:SQLiteObject;
  private isOpen:boolean;

  constructor(public http: Http, public storage: SQLite) {
    if(!this.isOpen){
      this.storage=new SQLite();

      //buat database bernama reminder.db
      this.storage.create({name:"reminder.db",location:"default"}).then((db:SQLiteObject) =>{
       this.db=db;

       //buat tabel bernama reminder
       db.executeSql("CREATE TABLE IF NOT EXISTS reminder(Idreminder INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, "+
        "description TEXT, date TEXT, time TEXT )",[]);
      
       this.isOpen=true;
      }).catch((error) => {
       console.log(error);
      })
     }
  }

  //insert ke tabel reminder
  InsertDataReminder(title: string, description:string, date:string, time:string ){
    return new Promise ((resolve, reject) => {
     let sql = "INSERT INTO reminder (title, description, date, time)"+
     "VALUES (?, ?, ?, ?)";
     this.db.executeSql(sql, [title, description, date, time]).then((data) =>{
      resolve(data);
     }, (error) => {
      reject(error);
     });
    });
  }

  //ambil semua data di tabel reminder
  GetAllDataReminder(){
    return new Promise ((resolve, reject) => {
     this.db.executeSql("SELECT * FROM reminder ORDER BY Idreminder DESC", []).then((data) => {
      let arrayDataReminder = [];
      if (data.rows.length > 0) {
       for (var i = 0; i < data.rows.length; i++) {
        arrayDataReminder.push({
          Idreminder: data.rows.item(i).Idreminder,
          title: data.rows.item(i).title,       
          description: data.rows.item(i).description,
          date: data.rows.item(i).date,
          time: data.rows.item(i).time
        });      
       }     
      }
      resolve(arrayDataReminder);
     }, (error) => {
      reject(error);
     })
    })
  }

  //ambil data Reminder berdasarkan Idreminder
  GetDataReminder(id:string){
    return new Promise ((resolve, reject) => {
     this.db.executeSql("SELECT * FROM reminder WHERE Idreminder=?", [id]).then((data) => {
      let arrayReminder = [];
      if (data.rows.length > 0) {
       for (var i = 0; i < data.rows.length; i++) {
        arrayReminder.push({
          Idreminder: data.rows.item(i).Idreminder,
          title: data.rows.item(i).title,       
          description: data.rows.item(i).description,
          date: data.rows.item(i).date,
          time: data.rows.item(i).time
        });      
       }     
      }
      resolve(arrayReminder);
     }, (error) => {
      reject(error);
     })
    })
  }

  //hapus data Reminder berdasarkan idreminder
  DeleteDataReminder(id:string){
    return new Promise ((resolve, reject) => {
     let sql="DELETE FROM reminder WHERE Idreminder=?";
     this.db.executeSql(sql, [id]).then((data) => {
      resolve(data);
     }, (error) => {
      reject(error);
     })
    })
  }

  //Update data Reminder berdasarkan id Reminder
  UpdateDataReminder(title: string, description:string, date:string, time:string, id:string){
    return new Promise ((resolve, reject) => {
     let sql="UPDATE reminder SET title=?, description=?, date=?, time=? WHERE IdReminder=?";
     this.db.executeSql(sql, [title, description, date, time, id]).then((data) => {
      resolve(data);
     }, (error) => {
      reject(error);
     })
    })
  }

}

Edit file home.html, disini kita akan membuat sebuah button input data dan list untuk menampilkan data reminder yang telah di inputkan.
<ion-header>
  <ion-navbar color="primary">
    <ion-title>
      Mari Belajar Coding
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h4 text-center>Membuat Aplikasi Reminder Ionic 3 SQLite dan Plugin Notification</h4>
  <h5 text-center>maribelajarcoding.com</h5><br>
  <button ion-button color="primary" block (click)="adddata()">Tambah Data</button>

  <ion-list *ngIf="ListDataReminder">
    <ion-card *ngFor="let data of ListDataReminder">
        <ion-card-content>
          <ion-row>
            <ion-col col-9>
                <h3><b>{{data.title}}</b></h3>
                <p>{{data.description}}<br>{{data.date}} {{data.time}}</p>
            </ion-col>
            <ion-col col-3 text-center no-padding >
              <button ion-button icon-only color="danger" small (click)="showConfirm(data.Idreminder)">
                <ion-icon name="trash"></ion-icon>
              </button>
              <button ion-button icon-only color="secondary" small (click)="editdata(data.Idreminder)">
                <ion-icon name="create"></ion-icon>
              </button>                         
            </ion-col>
          </ion-row>
        </ion-card-content>
      </ion-card>
</ion-list>
</ion-content>
Edit file home.ts, disini kita akan membuat sebuah fungsi untuk menampilkan data reminder sebagai array, pindah halaman input dan edit data serta membuat fungsi untuk menghapus data reminder. Kode lengkap file home.ts seperti dibawah ini, sudah diberi keterangan pada setiap fungsi.

import { Component } from '@angular/core';
import { NavController, AlertController, ToastController } from 'ionic-angular';

import { LocalNotifications} from '@ionic-native/local-notifications';

import { DatabaseProvider } from '../../providers/database/database';
import { InputDataPage } from '../input-data/input-data';
import { EditDataPage } from '../edit-data/edit-data';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public ListDataReminder : any;
  constructor(public navCtrl: NavController, public alertCtrl: AlertController, 
    public toastCtrl: ToastController, private localNotification:LocalNotifications,
    private database: DatabaseProvider) {
      
  }

  ionViewDidEnter() { 
    setTimeout(()=>{
      this.getalldatareminder();
    },500);  
    
  }

  //ambil semua data reminder yang berada pada tabel
  getalldatareminder(){
    this.database.GetAllDataReminder().then((data: any) => {
      this.ListDataReminder = data;      
    }, (error) => {
      console.log(error);
    });
  }

  //fungsi add data digunakan untuk pindah ke halaman input data
  adddata(){
    this.navCtrl.push(InputDataPage);
  }

  //fungsi edit data digunakan untuk pindah ke halaman edit data serta membawa parameter id
  editdata(id){
    this.navCtrl.push(EditDataPage,{
      Idreminder:id
    });
  }

  //Memuncilkan alert confirm
  showConfirm(id) {
    const confirm = this.alertCtrl.create({
      message: 'Apakah anda yakin akan menghapus data ini?',     
      buttons: [
        {
          text: 'Tidak',
          handler: () => {
            //console.log('Disagree clicked');
          }
        },
        {
          text: 'Ya',
          handler: () => {
            this.Hapus(id);
          }
        }
      ]
    });
    confirm.present();
  }

  Hapus(id){
    //hapus data reminder berdasarkan idreminder
    this.database.DeleteDataReminder(id).then(data => {
      let toast = this.toastCtrl.create({
        message: 'Data berhasil dihapus.',
        duration: 3000,
        position: 'bottom'
      });
      toast.present();
      this.getalldatareminder();
      //hapus data schedule notification berdasarkan idreminder
      this.localNotification.clear(id);
    }, (error) => {
      let toast = this.toastCtrl.create({
        message: error,
        duration: 3000,
        position: 'bottom'
      });
      toast.present();
    });
  }
}

Tampilan halaman home seperti dibawah ini.
Membuat Aplikasi Reminder Ionic 3 SQLite dan Local Notifications

Selanjutnya kita akan membuat sebuah form input data reminder. Edit file input-data.html yang berada pada src/input-data/input-data.html.
<ion-header>
  <ion-navbar color="primary">
    <ion-title>Buat Reminder</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <form [formGroup]="FormSimpanData" (ngSubmit)="simpan()">
    <ion-item>                                     
        <ion-label color="primary" stacked>Title</ion-label>
        <ion-input type="text" formControlName="title"></ion-input>                 
    </ion-item>  
    <ion-item>                                     
      <ion-label color="primary" stacked>Description</ion-label>
      <ion-input type="text" formControlName="description"></ion-input>                 
    </ion-item>  
    <ion-item>                                     
      <ion-label color="primary" stacked>Date</ion-label>
      <ion-datetime displayFormat="DD, MMM YYYY" pickerFormat="DD, MMM YYYY" formControlName="date" [(ngModel)]="data.date" ></ion-datetime>               
    </ion-item>    
    <ion-item>                                     
      <ion-label color="primary" stacked>Time</ion-label>
      <ion-datetime displayFormat="HH:mm" pickerFormat="HH:mm" formControlName="time" [(ngModel)]="data.time" ></ion-datetime>               
    </ion-item>      
    <ion-item>
      <button ion-button full type="submit" color="primary" [disabled]="!FormSimpanData.valid" >Simpan</button>
    </ion-item>    
  </form>
</ion-content>

Setelah membuat form input data, selanjutnya kita akan membuat fungsi untuk mengambil data dari form yang nantinya akan disimpan ke dalam database dan juga membuat schedule notification sesuai data yang diisikan di form. Edit file input-data.ts seperti dibawah ini.

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, AlertController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { LocalNotifications} from '@ionic-native/local-notifications';
import { DatabaseProvider } from '../../providers/database/database';
/**
 * Generated class for the InputDataPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-input-data',
  templateUrl: 'input-data.html',
})
export class InputDataPage {
  public FormSimpanData:FormGroup;
  data = { title:'', description:'', date:'', time:'' };
  constructor(public navCtrl: NavController, public navParams: NavParams,
    private formBuilder:FormBuilder, private localNotification:LocalNotifications, 
    public alertCtrl: AlertController, private toastCtrl: ToastController,
    private database: DatabaseProvider ) {
      this.FormSimpanData=this.formBuilder.group({
        title:[''],
        description:[''],
        date:[''],
        time:[''],
      });

  }

  simpan(){
    this.database.InsertDataReminder(this.FormSimpanData.value.title, this.FormSimpanData.value.description, 
      this.FormSimpanData.value.date, this.FormSimpanData.value.time).then( (data) => {

        let date = new Date(this.FormSimpanData.value.date+" "+this.FormSimpanData.value.time);
        this.localNotification.schedule({
          id: data['insertId'],
          title: this.FormSimpanData.value.title,
          text: this.FormSimpanData.value.description,
          trigger: {at: date},
          led: 'FF0000',
          sound: null
        });
        let alert = this.alertCtrl.create({
          title: '',
          subTitle: 'Notifikasi akan muncul pada '+date,
          buttons: ['OK']
        });
        alert.present();
        this.navCtrl.pop();
    }, (error) => {
      let toast = this.toastCtrl.create({
        message: error,
        duration: 3000,
        position: 'bottom'
      });
      toast.present();
   });
  }

}

Baris yang di beri highlight diatas merupakan fungsi untuk membuat schedule notification. Teman-teman bisa menambahkan sound, icon maupun mengubah trigger notifikasi. Lihat dokumentasi lengkapnya disini ionicframework.com/local-notifications

Tampilan form input data seperti dibawah ini.


Membuat Aplikasi Reminder Ionic 3 SQLite dan Local Notifications

Terakhir kita akan membuat sebuah form edit data reminder. Buka file edit-data.html yang berada pada src/edit-data/edit-data.html.
<ion-header>
  <ion-navbar color="primary">
    <ion-title>Edit Reminder</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <form [formGroup]="FormEditData" (ngSubmit)="simpan()">
    <ion-item>                                     
        <ion-label color="primary" stacked>Title</ion-label>
        <ion-input type="hidden" formControlName="Idreminder" *ngFor="let data of ListDataReminder" [value]="data.Idreminder"></ion-input>
        <ion-input type="text" formControlName="title" *ngFor="let data of ListDataReminder" [value]="data.title"></ion-input>                 
    </ion-item>  
    <ion-item>                                     
      <ion-label color="primary" stacked>Description</ion-label>
      <ion-input type="text" formControlName="description" *ngFor="let data of ListDataReminder" [value]="data.description"></ion-input>                 
    </ion-item>  
    <ion-item>                                     
      <ion-label color="primary" stacked>Date</ion-label>
      <ion-datetime displayFormat="DD, MMM YYYY" pickerFormat="DD, MMM YYYY" formControlName="date" *ngFor="let data of ListDataReminder" [(ngModel)]="data.date" ></ion-datetime>               
    </ion-item>    
    <ion-item>                                     
      <ion-label color="primary" stacked>Time</ion-label>
      <ion-datetime displayFormat="HH:mm" pickerFormat="HH:mm" formControlName="time" *ngFor="let data of ListDataReminder" [(ngModel)]="data.time" ></ion-datetime>               
    </ion-item>      
    <ion-item>
      <button ion-button full type="submit" color="primary" [disabled]="!FormEditData.valid" >Simpan</button>
    </ion-item>    
  </form>
</ion-content>

Buat fungsi edit data dan edit schedule notification di file edit-data.ts.
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, AlertController } from 'ionic-angular';
import { Validators, FormBuilder, FormGroup } from '@angular/forms';
import { LocalNotifications} from '@ionic-native/local-notifications';
import { DatabaseProvider } from '../../providers/database/database';
/**
 * Generated class for the EditDataPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-edit-data',
  templateUrl: 'edit-data.html',
})
export class EditDataPage {
  public FormEditData:FormGroup;
  public ListDataReminder : any;
  constructor(public navCtrl: NavController, public navParams: NavParams,
    private formBuilder:FormBuilder, private localNotification:LocalNotifications, 
    public alertCtrl: AlertController, private toastCtrl: ToastController,
    private database: DatabaseProvider) {
      this.FormEditData=this.formBuilder.group({
        Idreminder:[''],
        title:[''],
        description:[''],
        date:[''],
        time:[''],
      });
  }

  ionViewWillEnter() {   
    this.getdatareminder(); 
  }

  getdatareminder(){
    this.database.GetDataReminder(this.navParams.get('Idreminder')).then((data: any) => {
      this.ListDataReminder = data;  
      
    }, (error) => {
      console.log(error);
    });
  }

  simpan(){
    this.database.UpdateDataReminder(this.FormEditData.value.title, this.FormEditData.value.description, 
      this.FormEditData.value.date, this.FormEditData.value.time, this.FormEditData.value.Idreminder).then( (data) => {

        let date = new Date(this.FormEditData.value.date+" "+this.FormEditData.value.time);
        this.localNotification.schedule({
          id: this.FormEditData.value.Idreminder,
          title: this.FormEditData.value.title,
          text: this.FormEditData.value.description,
          trigger: {at: date},
          led: 'FF0000',
          sound: null
        });
        let alert = this.alertCtrl.create({
          title: '',
          subTitle: 'Notifikasi akan muncul pada '+date,
          buttons: ['OK']
        });
        alert.present();
        this.navCtrl.pop();
    }, (error) => {
      let toast = this.toastCtrl.create({
        message: error,
        duration: 3000,
        position: 'bottom'
      });
      toast.present();
   });
  }
}

Jalankan program menggunakan emulator atau real device. Buat sebuah reminder baru pada form input data, notifikasi akan muncul sesuai dengan jadwal yang telah di tentukan.


Membuat Aplikasi Reminder Ionic 3 SQLite dan Local Notifications

Tutorial membuat aplikasi reminder menggunakan ionic 3 sqlite dan local notifications telah selesai. Sekian, semoga bermanfaat.



Related search:
Ionic local notifications
Ionic 3 local notifications

Related Posts

Load comments