Performing basic database operations on an Ionic application using SQLite database

Successfully integrated the essential ngcordova SQLite plugin to develop a sample app.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="js/ng-cordova.js"></script>
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter">

    <ion-pane>

      <ion-header-bar class="bar-stable">
        <h1 class="title">Ionic Crud & SQLite</h1>
      </ion-header-bar>

      <ion-content ng-controller="AccountController">

          <form ng-submit="addAccount()">
            <div class="list">
              <label class="item item-input item-stacked-label">
                <span class="input-label">First Name</span>
                <input type="text" placeholder="John" ng-model="firstnameText">
              </label>
              <label class="item item-input item-stacked-label">
                <span class="input-label">Last Name</span>
                <input type="text" placeholder="Suhr" ng-model="lastnameText">
              </label>
              <div class="padding">
                <button class="button button-block button-positive">Create Account</button>
              </div>
            </div>
          </form>

          <ul class="list list-inset">
            <li class="item item-divider">
              {{accounts.length}} records
            </li>
            <li class="item" ng-repeat="account in accounts">
              <i class="icon ion-person"></i>  -  
              <span>{{account.firstname}} {{account.lastname}}</span>
            </li>
          </ul>

      </ion-content>

    </ion-pane>
  </body>
</html>

app.js

var db = null;

angular.module('starter', ['ionic', 'ngCordova'])

.run(function($ionicPlatform, $cordovaSQLite) {
  $ionicPlatform.ready(function() {

    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }

    db = $cordovaSQLite.openDB({ name: "my.db" });

    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXIST people (id integer primary key, firstname text, lastname text)");
  });
})

.controller('AccountController', function($scope, $cordovaSQLite) {

  $scope.accounts = function() {
    var query = "SELECT firstname, lastname FROM people";
    $cordovaSQLite.execute(db, query);
  }

  $scope.addAccount = function(){
    var query = "INSERT INTO people (firstname, lastname) VALUES (?, ?)";
    $cordovaSQLite.execute(db, query, [$scope.firstnameText, $scope.lastnameText]);
    $scope.firstnameText = '';
    $scope.lastnameText = '';
  }

});

While testing my application on my smartphone, I noticed that nothing was added to the list, indicating that data is not being saved to the database. Any assistance would be greatly appreciated. Thank you!

Answer №1

Encountered a similar issue and found a solution after doing some research. I made sure to wait for Cordova's deviceready event before loading Angular. To learn more about manually initializing Angular, refer to the API docs provided here

The key steps involved include removing the ng-app directive and triggering angular.bootstrap on the respective element post Cordova's deviceready event

To address this, I introduced a file named delayedAngular.js as shown below (do not forget to include it as a <script> in your index.html)

angular.element(document).ready(function() {
  console.log("BOOTSTRAPPING...");
  if (window.cordova) {
    document.addEventListener('deviceready', function() {
      console.log("window.cordova detected");
      angular.bootstrap(document.body, ['myCoolApp']);
    }, false);
  } else {
    console.log("window.cordova NOT detected");
    angular.bootstrap(document.body, ['myCoolApp']);
  }
});

In the provided snippet, make sure to replace myCoolApp with your main app module name. I will attempt to locate the source where I came across this information for proper acknowledgement.

I discovered it beneficial to utilize a WebSQL database as a fallback option for testing in the browser, especially since debugging SQLite on a device can be challenging. Here is an example of how I incorporated it into my app - it utilizes Angular promises, so ensure you are well-versed with them (additionally inject $window if alerts are desired. Unable to directly inspect the SQLite database on the device due to lack of rooting :-/)

var initDB = function(dbName){

  $log.log("Opening DB...");
  
  var q = $q.defer();
  var db;
  
  if($cordovaSQLite && $window.sqlitePlugin !== undefined){
    $window.alert("SQLite plugin detected");
    db = $cordovaSQLite.openDB({ name: dbName });
    q.resolve(db);
  }
  else {
    db = $window.openDatabase(
      dbName,
      "0.0.1",
      "My DB",
      200000,
      function(){
        $window.alert("Created WebSQL DB!");
      }
    );
    q.resolve(db);
  }
  
  return q.promise;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Switching out elements and tallying up values in an array

I am working with an array of identifiers for items var names = ['1','2', '1', '3']; Using these ids, I send an ajax request to retrieve the name associated with each id and replace it accordingly; var names = [ ...

Spontaneously fluctuate image transparency

I'm in need of some assistance with an issue I'm facing. I have 5 images positioned using Bootstrap and I want to add a fade animation to them on page load. Below is the code snippet I've been using, which works fine, but I would like the im ...

Is there a way to prevent the Material UI Chip component from appearing when there is no content present?

I have developed an application that pulls content from an API and displays it on the screen. Within this app, I have implemented a Material UI Card component to showcase the retrieved information, along with a MUI Chip component nested within the card. &l ...

When an error occurs during form validation, the input field should be highlighted to indicate the mistake

The following HTML code includes validation for Code and Mobile number input fields. The Code field will highlight in red and show an error message when empty or invalid entries are made, while the mobile field will display an error message without changin ...

Is it possible to replace the prototype of an object with a different object?

When an entity is generated, its prototype is established as another entity. Is it possible to alter the prototype of a previously created entity to point to a different object? ...

Angular allows me to pass a scope variable into a directive's link function, but unfortunately, not into the compile function

I need to pass a scope variable into a directive's compile function while using ng-repeat. I am familiar with doing this in the link function, but not in the compile function. Here is an example of my HTML: <div ng-repeat="item in chapter.mai ...

Can markdown generated HTML be bound to an Angular 4 component?

I'm currently using Angular 4 to develop an app similar to a wiki, allowing users to create their own pages and link them using a markdown text editor controlled by a component/directive. That's the goal, at least. For example: The custom markd ...

Eclipse fails to display AngularJS plugin

I downloaded the AngularJS plugin for Eclipse, but I can't seem to find it in the configuration section. ...

Sending data from a Javascript variable to Java in JSP

I need help with passing a Javascript value to a Java function in JSP. What is the best way to achieve this? The ID I want to pass comes from a combobox in JSP through Javascript. My goal is to extract the ID from the combobox and then pass it as a paramet ...

Tips for transferring the ngRepeat "template" to an ngDirective with transclude functionality

Example: http://plnkr.co/edit/TiH96FCgOGnXV0suFyJA?p=preview In my ng-directive named myDirective, I have a list of li tags generated using ng-repeat within the directive template. My goal is to define the content of the li tag as part of the myDirective ...

Creating a RESTful API using Express and Waterline ORM

I am currently working on constructing an API using Express and the Waterline ORM with a mongodb adapter. My main goal for doing this outside of Sails is to gain a deeper understanding of Waterline ORM, which will enable me to contribute to the development ...

The shadow effects and color overlays do not seem to be functioning properly in Mozilla Firefox

I have designed a popup registration form using the Bootstrap modal class. To ensure form validation, I have integrated some jQuery validation engine functionality. Additionally, I customized the appearance by adding a box shadow, adjusting the background ...

Tips for retrieving headers from a POST response using AngularJS $http

Before moving forward, it's important to note that this scenario occurs within a CORS environment. On Server #1 (http://localhost:33233), which is my main website hosting SOAP and WebAPI services, I have added the following lines to the Global.asax i ...

Integrate Ruby parameter into JavaScript in Rails

I have a div that I want to turn into a link to another page. Typically, we achieve this using link_to link. <% for item in @items %> <%= link_to "Item", item %> # -> or <%= link_to(item) %> <% end %> However, I need the ent ...

Express JS res.send() with an array response data is posing a concern during the Checkmarx scan

When using the axios library in my express middleware to retrieve responses from APIs, I encountered a security concern raised by Checkmarx scan report. router.post(someurl,req,res) { axios .get(someurl) .then((response=>{ **res.send(response.data);**/ ...

Combining Rails API with AngularJS and IonicFramework

I'm embarking on a new project and feeling unsure about my chosen setup/approach. The project involves creating a list directory that doesn't require high computing power. My initial plan is to develop a website using Rails Api and AngularJs (al ...

Immersive pop-up interface displaying a variety of embedded videos simultaneously

I am a beginner in JavaScript and I came across a CodePen that does exactly what I need, but it currently only works for one embedded video. What I aim to achieve is similar functionality, but with 6 videos. (function ($) { 'use strict'; ...

Measure the loading times of external web pages using JavaScript

I am seeking a minimalist approach to create a webpage on my server that utilizes JavaScript to calculate the loading time of the login page on various remote URLs/servers. These servers are dispersed globally, and my aim is to determine the quickest one f ...

Eliminate the hovering effect from images that are hyperlinked

I am feeling incredibly desperate as I have spent hours searching the internet for a solution with no success. When it comes to text links, I have included the following CSS code: a:hover img { border-bottom: none !important; } However, this code is als ...

Attempting to interpret HTML in Javascript

I have a text string that contains HTML tags. Initially, I attempted to insert this using innerHTML, but the tags were displayed as plain text. After some troubleshooting, I realized that I needed to properly parse the HTML content. Although jQuery prov ...