Re-run application sq lite database deleted in cordova - android

I am working in cordova. I created one database and table in it. It's work perfectly. But When I run application again database is not exist. It was deleted. I am using sqlite plugin https://github.com/litehelpers/Cordova-sqlite-storage
Please help me. I wasted my lots of time for that didn't get any solution.
My code for create database
define([
'cordova',
'logs'
], function () {
SQLiteDB = function () {
var self = this;
this.dbName = 'AppDb.s3db';
this.db = null;
/*
Populate database
*/
this.openDatabase = function (callback) {
this.db = sqlitePlugin.openDatabase({
name: this.dbName, location: 2, createFromLocation: 1
});
this.db.transaction(
function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS myDB(pax_id integer primary key, user_token text)');
if (typeof callback == 'function') {
callback.call();
}
},
this.dbErrorHandler
);
},
this.addLoginDetail = function (pax_id, user_token, successCallback) {
var that = this;
if (!this.db)
this.openDatabase();
that.db.transaction(
function (tx) {
tx.executeSql("INSERT INTO myDB (pax_id, user_token) VALUES (?,?)", [pax_id, user_token], function (tx, res) {
console.log("Save device config to local database");
Logs.logWrite("Save device config to local database");
if (typeof successCallback == 'function') {
var config_settings = null;
config_settings = JSON.parse(val.CONFIG_SETTINGS);
config_settings.LAST_UPDATE_TIME = lastUpdateTime;
if (!config_settings.APP_TYPE)
config_settings.APP_TYPE = 'D';
successCallback.call(config_settings);
}
});
},
that.dbErrorHandler
)
}
this.getLoginDetail = function (successCallback) {
var that = this;
console.log('call Login detail in local database');
Logs.logWrite('call getEmployee in local database');
if (!this.db)
this.openDatabase();
this.db.transaction(
function (tx) {
tx.executeSql("SELECT pax_id, user_token from myDB;", [],
function (tx, res) {
if (typeof successCallback == 'function') {
var employee = null;
var config_settings = null;
if (res.rows.length > 0) {
config_settings = JSON.parse(res.rows.item(0).config_settings);
console.log("dbLogin =============>> " + JSON.stringify(config_settings));
employee = res.rows.item(0);
}
successCallback.call(config_settings);
}
},
that.dbErrorHandler
)
},
that.dbErrorHandler
);
}
}
return SQLiteDB;
});

Updating your cordova version should resolve the issue.
and keep in mind that WebSQL API is depricated. It is unlikely to ever be supported on platforms that don't currently support it, and it may be removed from platforms that do.

Related

How to take sqlite db from ionic1 and store in external storage

I have created an app using ionic1 and it is live but some serious issues takes place in sqlite that is some datas are not updated in different tables. I would like to know is there any way to take the sqlite db from the app and save it in external storage using ionic1 and angular js. As well as i would like to know is it possible to again push the sqlite.db from external storage to the app and do the normal process.
You can do it by taking the database file out and make changes in the database and push the database again to the location
To Take the db from applicationstorage to external storage use this command:
function gotoDBBackup () {
var URI_DB = cordova.file.applicationStorageDirectory + 'databases/';
var PARENT_DIR = 'file://mnt/sdcard/';
var NAME_DB = 'DB.db';
var NEW_NAME_BACKUP = 'KPbackup.db';
window.resolveLocalFileSystemURL(URI_DB + NAME_DB, function (fs) {
window.resolveLocalFileSystemURL(PARENT_DIR, function (directoryEntry) {
fs.copyTo(directoryEntry, NEW_NAME_BACKUP, function () {
$log.log('The database backup was successful.');
alert('Backup ok');
});
});
});
}
To replace db use the command:
function replaceDB () {
/*window.resolveLocalFileSystemURL('file:///data/data/TestpatchKP/databases/DB.db', function (fs) {
var parent = 'file://mnt/sdcard/';
var newName = 'kpupdated.db';
window.resolveLocalFileSystemURL(parent, function (directoryEntry) {
fs.copyTo(directoryEntry, newName, function () {
alert('Backup ok');
}, failFiles);
});
}, failFiles);*/
var DATABASE_DIR = 'file://mnt/sdcard/';
var DB_NAME = 'kpupdated.db';
var NEW_NAME = 'DB.db';
var URI_DB = cordova.file.applicationStorageDirectory + 'databases/';
window.resolveLocalFileSystemURL(DATABASE_DIR + DB_NAME, function (fs) {
window.resolveLocalFileSystemURL(URI_DB, function (directoryEntry) {
fs.copyTo(directoryEntry, NEW_NAME, function () {
$log.log('Database has been restored successfully');
alert('Database restored successfully');
}, failFiles);
});
}, failFiles);
}
To remove a db :
function removeDB () {
var NEW_NAME = 'DB.db';
var URI_DB = cordova.file.applicationStorageDirectory + 'databases/';
window.resolveLocalFileSystemURL(URI_DB + NEW_NAME, function (fs) {
fs.remove(success, fail);
$log.log('Db removed successfully');
}, failFiles);
}
To view the database use the tool DB for browser. Hope it might help you.

How to pass a value between factorys in Ionic?

I need yours help.
I have two .factory's in Services.js
The first .factory works with a database, the second .factory with e-mail, files and so on.
How to pass a value from first factory to second? How to select data from the first factory?
//first factory
angular.module('starter.services', ['ngCordova', 'ngSanitize', 'ngCsv'])
.factory('NotesDataService', function ($cordovaSQLite, $ionicPlatform) {
var db, dbName = "CONTACTS_DB"
function useWebSql() {
db = window.openDatabase(dbName, "1.0", "Contacts database", 200000)
console.info('Using webSql')
}
function useSqlLite() {
db = $cordovaSQLite.openDB({name: dbName, location : 1})
console.info('Using SQLITE')
}
function initDatabase(){
$cordovaSQLite.execute(db, 'CREATE TABLE IF NOT EXISTS T_CONTACTS (id integer primary key, nom, prenom, codePostale, ville, email, portable)')
.then(function(res){
}, onErrorQuery)
}
$ionicPlatform.ready(function () {
if(window.cordova){
useSqlLite()
} else {
useWebSql()
}
initDatabase()
})
function onErrorQuery(err){
console.error(err)
}
return{
getAll: function(callback){
$ionicPlatform.ready(function () {
$cordovaSQLite.execute(db, 'SELECT * FROM T_CONTACTS').then(function (results) {
var data = []
for (i = 0, max = results.rows.length; i < max; i++) {
data.push(results.rows.item(i))
}
callback(data)
}, onErrorQuery)
})
}})
//second factory, here I need to get data from first factory
//to create a text file with the data from the database
// and attach this file to the e-mail
.factory('ContactsService', function ($ionicPlatform, $cordovaEmailComposer, $cordovaSQLite, $cordovaFile, NotesDataService) {
$ionicPlatform.ready(function () {
initCordovaEmailComposer();
})
function initCordovaEmailComposer() {
$cordovaEmailComposer.isAvailable().then(function () {
//is available
alert('avaible');
}, function () {
//not available
alert('not available');
})
}
return {
createEmail: function () {
var email = {
to: 'test#gmail.com',
cc: 'test#gmail.com',
bcc: 'test#gmail.com',
attachments: [
'file://cordova.file.externalDataDirectory/contacts.txt',
],
subject: 'Cordova Icons',
body: "Hello, mon ami",
isHtml: true
};
$cordovaEmailComposer.open(email).then(null, function () {
});
},
debugMessage: function (data) {
console.log('debug message', data);
},
createFile: function () {
var fileContacts = document.addEventListener('deviceready', function () {
NotesDataService.getAll(function (data) {
console.log(data)
return data
})
console.log('file contacts in console: ',fileContacts)
var fileName = 'contacts.txt'
var fileText = fileContacts
var filePath = cordova.file.externalDataDirectory
//CHECK file
$cordovaFile.checkFile(filePath, fileName).then(function (success) {
alert("file exist")
}, function (error) {
alert("file not exist", filePath)
//WRITE NEW FILE
$cordovaFile.writeFile(cordova.file.externalDataDirectory, fileName, fileText, true).then(function (success) {
// success
}, function (error) {
// error
});
});
})
},
}
})
Thank you all for your advice and support
Inject these factories into one another :
.factory('NotesDataService',['$cordovaSQLite','$ionicPlatform','ContactsService', function ($cordovaSQLite, $ionicPlatform,ContactsService) ....
.factory('ContactsService',['$ionicPlatform',.....,'NotesDataService', function ($ionicPlatform, $cordovaEmailComposer, $cordovaSQLite, $cordovaFile, NotesDataService) {
Now you can use either factory variables and functions in other factory.

IndexedDB – search for specific data? How to find the values from another value in a row?

Below is my example that I have. So far it does the following.
Enter in 3 values to a row
Retrieve all the values from all rows on load
Place all the values from each row and print them to screen that was
retrieved from the above step.
The part that I need help with is trying to find all the values of one row based on a value that exists in that row.
If a row contains the values name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ I would like to get all the data of that row when some one searches for ‘Andrew’
So far if you look at the function ‘searchItems’ you will see that I am trying to find data based on the value of the search input. The problem I am having is all I can get it to do is alert an “undefined” response.
How can I write the function to have it find things like described above
Also one step further. How can i edit the data that is in the row that was found based on the search input? (I have not written that function yet)
html
<!--jquery-2.1.4.js-->
<body>
<input type="text" id="dataGoesHere" />
<input type="text" id="moredataGoesHere" />
<input type="text" id="mostdataGoesHere" />
<button id="clickme">Save</button>
<div id="saved"></div>
<br><br>
<input type="text" id="searchString" />
<button id="search">search</button>
</body>
js
$(document).ready(function() {
myDb = function () {
var name = "test",
version = "1",
db,
testStoreName = "exampleStore",
testIndexName = "testIndexName",
addToTestIndex = false,
init = function () {
var deferred = $.Deferred(),
openRequest = indexedDB.open(name, version);
openRequest.onupgradeneeded = dbUpgrade;
openRequest.onsuccess = dbOpen;
openRequest.onerror = dbError;
return deferred.promise();
function dbUpgrade(evt) {
//here our db is at evt.target.result here we can adjust stores and indexes
var thisDb = evt.target.result, //the current db we are working with
newStore = thisDb.createObjectStore(testStoreName, {keyPath: "id", autoIncrement: true});
//Using indexes, you can target specific keys, this can be an array!
newStore.createIndex("testIndexKey", "testIndexKey", {unique : false});
console.log("Doing an upgrade");
}
function dbOpen(evt) {
console.log("DB successfully opened");
db = evt.target.result;
deferred.resolve();
getAllItems (function (items) {
var len = items.length;
for (var i = 0; i < len; i += 1) {
console.log(items[i]);
$('#saved').append('<p>'+items[i].item + ' ' + items[i].george + ' ' + items[i].column3 + ' ' + items[i].id + '</p>');
}
});
}
function dbError(error) {
console.log("DB Error");
console.log(error);
deferred.reject(error);
}
},
add = function(item, bob, villa) {
var itemToAdd = {"item" : item, "george" : bob, "column3" : villa},
objStore,
request,
deferred = $.Deferred();
if (!addToTestIndex) {
//here we will add half the entries to the index
//See http://stackoverflow.com/questions/16501459/javascript-searching-indexeddb-using-multiple-indexes for a better example
addToTestIndex = !addToTestIndex;
itemToAdd.testIndexKey = "This is a test";
}
//first get the object store with the desired access
objStore = db.transaction([testStoreName], "readwrite").objectStore(testStoreName);
//next create the request to add it
request = objStore.add(itemToAdd);
request.onsuccess = function (evt) {
deferred.resolve(evt.target.result);
};
request.onerror = function (evt) {
deferred.reject(evt);
};
return deferred.promise();
},
get = function (index) {
//Since our store uses an int as a primary key, that is what we are getting
//The cool part is when you start using indexes...
var deferred = $.Deferred(),
store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
request = store.get(parseInt(index));
request.onsuccess = function (evt) {
console.log(evt);
deferred.resolve(evt.target.result);
};
request.onerror = function (evt) {
deferred.reject("DBError: could not get " + index + " from " + testStoreName);
};
return deferred.promise();
},
getAllItems = function(callback) {
var trans = db.transaction(testStoreName, IDBTransaction.READ_ONLY);
var store = trans.objectStore(testStoreName);
var items = [];
trans.oncomplete = function(evt) {
callback(items);
};
var cursorRequest = store.openCursor();
cursorRequest.onerror = function(error) {
console.log(error);
};
cursorRequest.onsuccess = function(evt) {
var cursor = evt.target.result;
if (cursor) {
items.push(cursor.value);
cursor.continue();
}
};
},
searchItems = function(searchString) {
var deferred = $.Deferred(),
store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
request = store.get(searchString);
request.onerror = function(event) {
// Handle errors!
alert("error");
};
request.onsuccess = function(event) {
alert('start seach')
// Do something with the request.result!)
alert(event.target.result);
alert('end search')
};
};
return {
init: init,
get: get,
add: add,
getAllItems: getAllItems,
searchItems: searchItems
};
}
var db = new myDb();
db.init().then(function () {
$("#clickme").click(function(evt) {
//add, then we will get the added item from the db
console.log("Adding new item to db");
db.add($('#dataGoesHere').val(), $('#moredataGoesHere').val(), $('#mostdataGoesHere').val())
.then(function (res) {
return db.get(res);
})
.then(function (res) {
$('#saved').append('<p>'+res.item+' '+res.george+' '+res.column3+'</p>');
});
});
$("#search").click(function(evt) {
// search for a specific row
console.log("searching");
db.searchItems($('#searchString').val());
});
})
});
First thing (and could be the probable cause): Are you having an index on the key you are trying to search? In you case, for data as name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ if you trying to search for "Andrew", then you should be having an index created on "name". If it is not there then you will not be able to make a search and that's what probably could be happening.
Next: In the data store there could be more than one rows with name as Andrew, so you can have a cursor open using the index and then loop through all value and get the desired one. Something like (I am just throwing you an idea through this code snippet):
var objectStoreHandler = transaction.objectStore(selectDataObj.tblName);
var indexHandler = objectStoreHandler.index(selectDataObj.whereColObj.whereColNameArr[0]);
var cursorHandler = indexHandler.openCursor(keyRange);
cursorHandler.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
console.log("!!!!!");
if (cursor.value != null && cursor.value != undefined) {
resultArr.push(cursor.value);
}
cursor["continue"]();
} else {
console.log("################### " + resultArr);
return successCallBack(resultArr);
}
return;
};

PhoneGap SQLite error? Uncaught TypeError: Object #<Object> has no method 'exec'

I m developing Android application. I'm integrating the sqlite into my application https://github.com/brodyspark/PhoneGap-sqlitePlugin-Android
The below error is coming
Uncaught TypeError: Object # has no method 'exec'
while using the following code
window.sqlitePlugin.openDatabase({name: "DB"});
You need to ensure you have waited for Cordova to load prior to opening a database.
As per the README.md from the project:
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
// ...
}
https://github.com/xuexueMaGicK/Gift-App
see this link js file is available here database connection are there
window.addEventListener("DOMContentLoaded", init);
function init() {
pageshow = document.createEvent("Event");
pageshow.initEvent("pageshow", true, true);
tap = document.createEvent("Event");
tap.initEvent("tap", true, true);
pages = document.querySelectorAll('[data-role="page"]');
numPages = pages.length;
links = document.querySelectorAll('[data-role="link"]');
numLinks = links.length;
//checkDB();
document.addEventListener("deviceready", checkDB, false);
}
/*******************************
General Interactions
*******************************/
function checkDB() {
navigator.splashscreen.hide();
database = openDatabase('data', '', 'data', 1024 * 1024);
if (database.version === '') {
database.changeVersion('', '1.0', createDB, function (tx, err) {
console.log(err.message);
}, function (tx, rs) {
console.log("Increment transaction success.");
});
addNavHandlers();
} else {
addNavHandlers();
}
}
function createDB(db)
{
/*******Create Table Gifts********/
db.executeSql('CREATE TABLE "gifts" ("gift_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_id" INTEGER, "occasion_id" INTEGER, "gift_idea" VARCHAR(45))', [], function (tx, rs) {
console.log("Table gifts created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Names********/
db.executeSql('CREATE TABLE "names" ("name_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table names created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Occasions********/
db.executeSql('CREATE TABLE "occasions" ("occasion_id" INTEGER PRIMARY KEY AUTOINCREMENT, "occasion_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table occasions created");
}, function (tx, err) {
console.log(err.message);
});
}
In Manifest.xml u have to add plugins related to the SQLite.Then it will work.

how to import multiple sql file in android db using jquery

I have multiple sql file in my assets folder and building app on android. I want this sql to import in android app database on by one using jquery. How to do that please help. I have done code for single file but i want it for multiple sql file.
var filePath = 'database/crmaaaa_1.sql';
//alert(filePath);
$.get(filePath, function (response) {
var statements = response.split('\n');
var shortName = "crm1";
var version = '1.0';
var displayName = 'crm1';
var maxSize = 40000000; // bytes
// db = openDatabase(shortName, version, displayName, maxSize);
var db = window.openDatabase(shortName, version, displayName, maxSize);
// db.transaction(populateDB, errorCB);
db.transaction(function (transaction) {
jQuery.each(statements, function (index, value) {
// alert("query"+value);
if (value != '') {
transaction.executeSql(value, [], successHandler, function (e) {
alert("Error executing sql " + value);
});
}
});
});
});
You can create an array of sql files to import:
var sqlFiles = ['file1.sql', 'file2.sql', 'file3.sql'];
$(sqlFiles).each(function() {
$.get(this, function (response) {
// your sql file management
// ...
}
});
This should get you to the goal.

Categories

Resources