How to use database sqlite in android device?


#1

Hy guys, I have a project ionic with platform android, I want to use database sqlite (example MyApp.db) in Android device.I do it as follow. please read clearly 5 steps.

  1. Create new project , copy database MyApp.db (6 tables and some rows data) to root/www (old version root/platforms/android/assets ) in project

  2. In services.js , copy database if not exits

    .factory(‘ToList’, function ($rootScope, $cordovaSQLite, $q, $cordovaDialogs) {
    return {
    initDatabase: initDatabase,
    }
    function initDatabase() {
    if (window.cordova) {
    ////// App syntax, Android device
    window.plugins.sqlDB.copy(“MyApp.db”, function () {
    $rootScope.db = $cordovaSQLite.openDB(“MyApp.db”);
    }, function (error) {
    $rootScope.db = $cordovaSQLite.openDB(“MyApp.db”);
    });
    } else {
    //////// Ionic serve syntax , Chrome, Firefox
    $rootScope.db = window.openDatabase(“MyApp.db”, ‘1.0’, ‘App Demo’, 2000000);
    var sql = ‘CREATE TABLE IF NOT EXISTS [Category] ([CatID] CHAR(5) NOT NULL, [Name] NVARCHAR(50));
    CREATE TABLE IF NOT EXISTS [Product] ([CatID] CHAR(5) NOT NULL,[ProID] CHAR(5), [Name] NVARCHAR(50));’;
    var sub = sql.split(’;’);
    for (var i = 0; i < sub.length; i++) {
    $cordovaSQLite.execute($rootScope.db, sub[i]);
    }
    }
    return true;
    }
    });
    And app.js

    .run(function ($ionicPlatform, ToList) {
    $ionicPlatform.ready(function () {
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    cordova.plugins.Keyboard.disableScroll(true);
    }
    if (window.StatusBar) {
    StatusBar.styleLightContent();
    }
    ToList.initDatabase();
    });
    })
    3)Run: ionic build android , I see MyApp.db copy at root/platforms/android/assets/www in project , then run : ionic run android deploy app in android device.

  3. Check in Android device ,Open and i see at : Internal Storage>Android>data>com.ionicframework.myapp596823>cache folder and files folder

  4. Open app in android device, i can get some rows data .
    Look seem it’s work ,but when i close app in android device and reopen it , i can not get data .
    Can yoy tell me what’s the problem in here ?
    Thank guys.


#2

I am facing the same problem.Every time i close the app seems like DB is getting deleted.


#3

Has anyone got a solution for this issue? The sqlite database seems to work for ios but not for android