Ionic 6 Cordova SQLite Offline Storage Tutorial
Ionic 6 Sqlite data storage tutorial; In this detailed guide, we will explain how to add SQlite storage in the Ionic Angular application.
Furthermore, we also learn how to set, get, remove, delete data from offline device’s storage using the Cordova and Ionic Native SQLite storage plugin.
In web browsers, we mainly depend on Local storage objects to store the data locally, whereas, in mobile devices, Cordova offers an impeccable option to create an offline application.
The SQLite package allows you to access the SQLite databases on the devices and that too easily and quickly. For whatever platform you are building an app, don’t worry; SQLite covers all the major platforms, such as Android, iOS, macOS, not only but also Windows.
SQLite is a relational database management system made with a C library. Ideally, the SQLite database is primarily embedded into the device, and it helps store the data on the device’s local storage.
Device storage is mainly helpful for storing helpful information related to mobile applications. The good thing about it is that the data don’t go away unless the application is completely removed or the phone is formatted.
Apart from this telling you how to use SQLite database in Ionic to build an Offline application, we also have another tutorial for you that you can check out using given below link.
Read more: How to create CRUD operations in Ionic using SQLite Database?
Ionic 6 Offline Storage Integration Example
- Step 1: Install Ionic Application
- Step 2: Install SQLite Storage Plugin
- Step 3: Add Storage Module in AppModule Class
- Step 4: Access Storage API in Ionic
- Step 5: Set Key/Value
- Step 6: Get Key/Value
- Step 7: Remove Storage Value
- Step 8: Get All Stored Keys
- Step 9: Test Application
Install Ionic Application
First and foremost thing, install Ionic CLI tool:
npm install -g @ionic/cli
Then, install a new Ionic Angular blank application:
ionic start ionic-sqlite-storage-example blank --type=angular
Use command to get inside the project:
cd ionic-sqlite-storage-example
Install SQLite Storage Plugin
Open terminal, type given below commands in the console. Both the commands will install Ionic native and Cordova storage plugin.
ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic/storage
Add SQLite Storage Module in AppModule Class
Import SQLite module from the ‘@ionic-native/sqlite/ngx’ package, plus register in the providers’ array into the AppModule class.
Open and place the following code in app.module.ts file:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
// Import storage module
import { IonicStorageModule } from '@ionic/storage';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
IonicStorageModule.forRoot()
],
providers: [
{
provide: RouteReuseStrategy,
useClass: IonicRouteStrategy
}
],
bootstrap: [AppComponent],
})
export class AppModule {}
Access Storage API in Ionic
Accessing native storage throughout the application is easy and quick; import the Storage module, add it into the constructor method. After that, you can set the key-value pair similarly to get the key-value pair, and you can check out the response on the console log.
import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(private storage: Storage) {
// set a key/value
this.storage.set('name', 'Max');
// Or to get a key/value pair
this.storage.get('age').then((val) => {
console.log('Your age is', val);
});
}
}
Set Key/Value
Access set()
method using storage plugin, this method takes key and value through which you can set or add value in a key. It returns a promise response and lets you know whether the value is added to the key.
// set a key/value
setValue(key: string, value: any) {
this.storage.set(key, value).then((res) => {
console.log('set' + key + ' ', res);
// fetch key-value stored in key
this.getKeyValue(key);
}).catch((error) => {
console.log('Error ' + key + ' ', error);
});
}
Get Key/Value
The get()
method takes the key as a parameter and is accessed via the storage module; consequently, it returns the promise along with the value related to the passed key property.
// fetch a key/value
getKeyValue(key: string) {
this.storage.get(key).then((res) => {
this.data[key] = "";
this.data[key] = res;
}).catch((err) => {
console.log('Error ' + key + '', err);
});
}
Remove Storage Value
The remove()
method removes the value related to the passed key from the offline storage in ionic.
// Remove key/value
deleteKey(key: string) {
this.storage.remove(key).then(() => {
alert('Deleted ' + key);
this.data[key] = "";
}).catch((err) => {
alert(err);
});
}
Get All Stored Keys
The storage API provides THE keys()
method, and It gets all the stored keys through the promise.
// Get all stored key/value
allStoredKeys() {
this.storage.keys().then((res) => {
this.getStoredKeys = res;
});
}
Final Code Example
Here is the final code from which you can compare your code for using offline storage in the Ionic app:
Open home.page.html page and add the suggested code:
<ion-header [translucent]="true">
<ion-toolbar>
<ion-title>
Ionic Offline or Native Storage Example
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content [fullscreen]="true">
<ion-grid>
<ion-row>
<ion-col>
<strong>String value:</strong>
</ion-col>
<ion-col>:
{{data.name}}<ion-icon name="trash" (click)="deleteKey('name')"></ion-icon>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<strong>Integer value:</strong>
</ion-col>
<ion-col>:
{{data.phone}}<ion-icon name="trash" (click)="deleteKey('phone')"></ion-icon>
</ion-col>
</ion-row>
<ion-item-divider></ion-item-divider>
<ion-row>
<ion-col>
<strong>All Stored Keys:</strong>
</ion-col>
<ion-col>
{{ getStoredKeys }}
</ion-col>
</ion-row>
<ion-item-divider></ion-item-divider>
<ion-row>
<ion-col>
<strong>User JSON object:</strong>
<ion-icon name="trash" (click)="deleteKey('users')"></ion-icon>
<ion-card *ngFor="let user of data.users; let i = index">
<ion-card-header>
<ion-card-title>User {{i + 1}}</ion-card-title>
</ion-card-header>
<ion-card-content>
<p><strong>Name</strong>: {{user.name}}</p>
<p><strong>Email</strong>: {{user.email}}</p>
<p><strong>Username</strong>: {{user.username}}</p>
</ion-card-content>
</ion-card>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
Hence, open home.page.ts file and update the following code:
import { Component, OnInit } from '@angular/core';
import { Storage } from '@ionic/storage';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
data: any;
getStoredKeys: any;
constructor(
private storage: Storage
) {
this.data = {};
//Set String Value
this.setValue("name", "Remotestack");
//Set Integer Value
this.setValue("phone", 5555599999);
let userObj = [
{
name: "Leanne Graham",
username: "Bret",
email: "Sincere@april.biz"
},
{
name: "Ervin Howell",
username: "Antonette",
email: "Shanna@melissa.tv"
}
];
// Set object val
this.setValue("users", userObj);
}
ngOnInit(): void {
this.allStoredKeys();
}
// set a key/value
setValue(key: string, value: any) {
this.storage.set(key, value).then((res) => {
console.log('set' + key + ' ', res);
// fetch key-value stored in key
this.getKeyValue(key);
}).catch((error) => {
console.log('Error ' + key + ' ', error);
});
}
// fetch a key/value
getKeyValue(key: string) {
this.storage.get(key).then((res) => {
this.data[key] = "";
this.data[key] = res;
}).catch((err) => {
console.log('Error ' + key + '', err);
});
}
// Remove key/value
deleteKey(key: string) {
this.storage.remove(key).then(() => {
alert('Deleted ' + key);
this.data[key] = "";
}).catch((err) => {
alert(err);
});
}
// Get all stored key/value
allStoredKeys() {
this.storage.keys().then((res) => {
this.getStoredKeys = res;
});
}
}
Test Application
In this step, you need to add the platform, create a runnable build and run the app: Hence, go ahead and follow the given instructions:
# iOS
ionic cordova platform add ios
# Android
ionic cordova platform add android
Use following command to create the build.
# iOS
ionic cordova build ios
# Android
ionic cordova build android
Ultimately, with the help of given below command start the application on the device.
# iOS
ionic cordova run ios -l
# Android
ionic cordova run android -l
Conclusion
Finally, we have completed the Ionic Angular SQLite tutorial. In this tutorial, we learned how to use SQLite storage in an Ionic app with the help of Cordova and Ionic native SQlite package.
Additionally, we simply learn how to add or set the data in offline storage, how to get value or data from device storage, and how to remove offline data from device storage.