Ionic 7 Cordova SQLite Offline Storage Tutorial

Last Updated on by in Ionic

Ionic 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 Offline Storage Integration Example

  • Step 1: Install Ionic Application
  • Step 2: Install SQLite Storage Plugin
  • Step 3: Access Storage API in Ionic
  • Step 4: Set Key/Value
  • Step 5: Get Key/Value
  • Step 6: Remove Storage Value
  • Step 7: Get All Stored Keys
  • Step 8: Test Application

Install Ionic Application

First and foremost thing, install Ionic CLI tool:

sudo 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

Disable Strict Type Errors

To avoid TypeScript compiling issues, we just need to open tsconfig.json file:

First, set below property under “compilerOptions” property.

"compilerOptions": {
    "strictPropertyInitialization": false,
    "skipLibCheck": true
    ...
}

Secondly, add given props under “angularCompilerOptions”.

"angularCompilerOptions": {
    "strictTemplates": false,
    ...
}

Install SQLite Storage Plugin

Open terminal, type given below commands in the console. Both the commands will install Ionic native and Cordova storage plugin.

npm i cordova-sqlite-storage
npm install --save @ionic/storage

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; you can check out the response on the console log.

Add code in home/home.page.ts file:

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

By default, the @ionic-native/core plugin is not available in our app’s package.json file.

Run the below command to add the native core package.

npm install @ionic-native/core --legacy-peer-deps

Next, 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

Ionic native offline storage

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.

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.