Database and local Storage get cleared in IOS phonegap application - javascript

About App -
I am using corodova 2.1.0 in ios phonegap application.
My app does some registration process in that it checks if the app is registered or not if it found data in database or local storage it goes to dashboard else it ask for registration.
In registration process app ask for mobile no if mobile entry from back end is fond then app will download data from database and stores it in localstorage and database.
Issue-
if is give registered for first time app downloads data and goes to dashboard. and if i kill the app and then open it it will ask for registration and if i registered second time and after going on dashboard if i kill app and open again app then it will shows dasboard afterwords it donesn't show registration screen.
I checked on weinre first time also it loads all data in database and local sotrage.
i am storing only name and user's id. but it get cleared if i kill app after first installation.
//Here is code which checks that user is registred or not
// this will ckeck on splashscrenn
//$window.location.href = '#/SplashScreen';
function checkregistration(){
var sqlU = 'SELECT ClubId, MemberId, MemberName FROM member_master_dtls';
var obj = {};
var db = window.openDatabase("ROW_DB", "", "Cordova Demo", 200000);
try{
var MID = localStorage.getItem('MyMemberID');
console.log("MID befo "+ typeof(MID));
console.log("MID === "+ (MID));
if ( MID.length>0)
{
console.log("MID"+ MID);
RowDbService.CheckVersion();
$window.location.href = '#/Dashboard';
}else{
db.transaction(function(tx) {
//console.log('in db trans');
tx.executeSql(sqlU, [], SuccessChkMemlst_local, errorCB);
});
}
}
catch(err){
db.transaction(function(tx) {
//console.log('in db trans');
tx.executeSql(sqlU, [], SuccessChkMemlst_local, errorCB);
});
}
}
function SuccessChkMemlst_local(tx, results) {
//alert("success splash");
//console.log("successlist = " + results.rows.length);
if (results.rows.length == 0) {
//localStorage.setItem('globalx', '1');
globalx = 1;
$window.location.href = '#/Register';
//console.log(results);
} else {
RowDbService.CheckVersion();
$window.location.href = '#/Dashboard';
}
}
=================================
//here is function on Register page that download data from webservice and store it in database
//$window.location.href = '#/Register';
function ChkForRegistration(){
//here some webservices wich downloads th
localStorage.setItem('ClubID', obj[0].ClubId);
localStorage.setItem('MyMemberName', obj[0].member_name);
localStorage.setItem('MyMemberID', obj[0].member_master_id);
localStorage.setItem('MyClubName', obj[0].club_name);
localStorage.setItem('NewsCount',0);
localStorage.setItem('AnnCount',0);
localStorage.setItem('EventCount',0);
localStorage.setItem('BdayCount',0);
localStorage.setItem('EventDate',"");
localStorage.setItem('BdayDate',"");
var datarow = {};
datarow.MemberId = localStorage.getItem('MyMemberID');
datarow.MemberName = localStorage.getItem('MyMemberName');
datarow.ClubId = localStorage.getItem('ClubID');
datarow.ClsfyName = localStorage.getItem('MyClubName');
var db = window.openDatabase("ROW_DB", "", "Cordova Demo", 200000);
db.transaction(function(tx) {
var query="insert into member_master_dtls (id,MemberId,MemberName,ClubId,ClsfyName) values(?,?,?,?,?)";
tx.executeSql("update sqlite_sequence set seq = 0 where name ='member_master_dtls'");
tx.executeSql("delete from member_master_dtls");
tx.executeSql(query,[(1),datarow.MemberId,datarow.MemberName,datarow.ClubId,datarow.ClsfyName]);
tx.executeSql("update sqlite_sequence set seq =1 where name ='member_master_dtls'");
});
$window.location.href = '#/Dashboard';
}

Related

Doing Backup DB from Stored Procedure works in local but no in production

i need to backup my database by a clic button on a web app. I put the code in a SP which is called by the clic, it create a .bak and store it in a server folder.
This works perfectly executing the SP directly in SQL SERVER, clicking the button in local web app, but no in production.
The code in local and production are the same.
I tried to do the BK in many ways:
backup database DATABASENAME to disk = #route
set #query = 'backup database DATABASENAME to disk = ' + '''' + #route + ''''
exec(#query)
Catching the info in a variable.
set #query = 'backup database DATABASENAME to disk = ' + '''' + #route + ''''
exec #respuesta = sp_executesql #query
Again, all of these ways works in local but no in production.
Here is my SP:
ALTER procedure [dbo].[sp_IWBackupDatabase]
as
begin
declare #route nvarchar(500), #query nvarchar(1000), #respuesta int = 1
set nocount on
set #route = 'I:\SERVERFOLVER\BackupDB\DATABASENAMEFull.bak'
begin try
backup database DATABASENAME to disk = #route
set #respuesta = 0
end try
begin catch
set #respuesta = 1
end catch
select #respuesta Respuesta
end
Here is my call in with JS:
function BackupDatabase() {
$.post('main.php', {
action: 'BackupDatabase'
}, function(e) {
if (e.error) {
if (e.r == "SQLSTATE[IMSSP]: The active result for the query contains no fields.") {
Core.ShowNotific8('It WORKS', 'lime', false);
DBWasBackUp = 1;
$('#btn_CreateDBBK').attr('disabled', 'disabled');
} else {
Core.ShowNotific8('It NOT WORKS', 'ruby', false);
DBWasBackUp = 0;
$('#btn_CreateDBBK').removeAttr('disabled');
}
} else {
if (e.r[0]['Respuesta'] == '0') {
Core.ShowNotific8('It WORKS', 'lime', false);
DBWasBackUp = 1;
$('#btn_CreateDBBK').attr('disabled', 'disabled');
} else {
Core.ShowNotific8('It NOT WORKS', 'ruby', false);
DBWasBackUp = 0;
$('#btn_CreateDBBK').removeAttr('disabled');
}
}
});
return false;
}
Finally, here is the call from PHP:
function BackupDatabase()
{
$cnx = $this->connectSqlSrv():
$sth = $cnx->prepare("Exec sp_IWBackupDatabase");
$retval json_encode($retval);
}
It is likely permissions. When you are running the site under VS the user is running as your local windows user. When you deploy to IIS it is running as the application pool user. Check what user this is running under by going to IIS > Sites > Right Click The Site > Manage WebSite > Advanced Settings. That is the user it is running as and that user may need to have SQL access. If you need to add a new application pool look here:https://learn.microsoft.com/en-us/iis/configuration/system.applicationhost/applicationpools/add/#how-to

titanium iOS app for adhoc distribution stuck on splash screen

I'm running a titanium iOS application, it works as expected on the simulator and also on the device when I run it from appcelerator studio, however when I package the app for adhoc distribution and install it on my iPhone device via iTunes it just gets stuck on the splash screen.
Also I can not debug because it is adhoc distribution. The only thing I noticed using alerts is that it runs through alloy.js but never gets to index.js
Any help would be appreciated.
edit: these are my index and alloy files.
index.js
// Arguments passed into this controller can be accessed via the `$.args` object directly or:
var args = $.args;
var webServices = require("webService");
var TAG = "[loginActivity.js] : ";
var fb = Alloy.Globals.Facebook;
var win = $.window;
var core = require("core");
var network = require("NETWORK");
sessionStatus = Ti.App.Properties.getBool('session');
console.log("session estatus "+sessionStatus);
if(!sessionStatus)
Ti.App.Properties.setBool('session', false);
sessionStatus = Ti.App.Properties.getBool('session');
console.log("session estatus "+sessionStatus);
Ti.App.session=sessionStatus;
manageLogin();
Ti.App.addEventListener('resumed',function(e){
//check if login is still valid
console.log("hola");
manageLogin(); //I just reuse my login logic on resume
});
function manageLogin(){
if(Ti.App.session==false){
// require("core").openLogin;
console.log("abro login");
openLogin();
}else{
console.log("abro main");
Ti.App.User_id= Ti.App.Properties.getInt('User_id');
//Ti.App.profIm =Ti.App.Properties.getObject('image');
require("core").openMainActivity();
}
}
function openLogin(){
console.log("First attempt to use geolocation services.");
var hasLocationPermissions = Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE);
Ti.API.info('Ti.Geolocation.hasLocationPermissions', hasLocationPermissions);
if (hasLocationPermissions) {
console.log("GPS permissions granted.");
open();
} else {
console.log("Second attempt");
Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE, function(e) {
if (e.success) {
// $.index.open();
open();
} else {
console.log("Something happened during second attempt");
if (OS_ANDROID) {
//alert('You denied permission for now, forever or the dialog did not show at all because you denied it forever earlier.');
var activity = Titanium.Android.currentActivity;
activity.finish();
open();
}
// We already check AUTHORIZATION_DENIED earlier so we can be sure it was denied now and not before
Ti.UI.createAlertDialog({
title : 'You denied permission.',
// We also end up here if the NSLocationAlwaysUsageDescription is missing from tiapp.xml in which case e.error will say so
message : e.error
}).show();
}
});
}
}
function open(e) {
var nextWin = core.createWindow({
controllerName : "loginActivity"
});
if (OS_ANDROID) {
nextWin.fbProxy = Alloy.Globals.Facebook.createActivityWorker({lifecycleContainer: nextWin});
}
nextWin.addEventListener("postlayout", function checkGPS(e){
nextWin.removeEventListener("postlayout", checkGPS);
if(Ti.Geolocation.getLocationServicesEnabled() === false) {
if(OS_ANDROID){
var alertDlg = Titanium.UI.createAlertDialog({
title:'GPS apagado',
message:'El GPS está apagado. Enciéndelo en ajustes.',
buttonNames: ['No encender el gps', 'Abrir ajustes']
});
alertDlg.cancel = 0;
alertDlg.addEventListener('click', function(e){
if(!e.cancel) {
//open up the settings page
var settingsIntent = Titanium.Android.createIntent({
action: 'android.settings.LOCATION_SOURCE_SETTINGS'
});
Titanium.Android.currentActivity.startActivity(settingsIntent);
}
});
alertDlg.show();
}
else {
alert("No se detecta tu ubicación, te recomendamos encender el GPS antes de iniciar la aplicación.");
}
}
});
nextWin.open();
}
and alloy.js
(function(){
var ACS = require('ti.cloud'),
env = Ti.App.deployType.toLowerCase() === 'production' ? 'production' : 'development',
username = Ti.App.Properties.getString('acs-username-'+env),
password = Ti.App.Properties.getString('acs-password-'+env);
// if not configured, just return
if (!env || !username || !password) { return; }
/**
* Appcelerator Cloud (ACS) Admin User Login Logic
*
* fires login.success with the user as argument on success
* fires login.failed with the result as argument on error
*/
ACS.Users.login({
login:username,
password:password,
}, function(result){
Ti.API.info("Yes, logged in.");
if (env==='development') {
Ti.API.info('ACS Login Results for environment `'+env+'`:');
Ti.API.info(result);
}
if (result && result.success && result.users && result.users.length){
Ti.App.fireEvent('login.success',result.users[0],env);
} else {
Ti.App.fireEvent('login.failed',result,env);
}
});
})();
Alloy.Globals.Facebook = require('facebook');
var T = function (name) {
return require('T/' + name);
};
T('trimethyl');
var Notifications = T('notifications');
Notifications.onReceived = function(e) {
console.log("onreceived "+JSON.stringify(e));
alert(e.data);
};
Notifications.subscribe();
console.log("token "+Notifications.getRemoteDeviceUUID());
For future references.
I had to test step by step, block by block and line by line using a single alert at a time to find out what part of the code was causing the application to crash.
I did find out that 2 separate files were calling each other like require("file2") in file 1 and require("file1") in file 2. Although I don't know why this problem/bug/whatever happened only in distribution ad-hoc mode and not when running the app directly from the computer.

Chrome Deleting WebSQL Database Between Requets

So i'm trying to create an offline app with AngularJS as the front-end and Play! 1.2.5 as the back-end. On the client side, I created 2 pages - main.html and login.html where upon submitting the form on login.html, a WebSQL database is created
var db = openDatabase("users", "1.0", "User Database", 2*1024*1024
some data is added in and the user is forwarded to main.html.
The problem is that when I call
var db = openDatabase("users", "1.0", "User Database", 2*1024*1024);
on main.html, I get the database but with none of the information created on the login.html page. What is going on here?
EDIT: Here's some code
login.html (JavaScript section):
var db = window.openDatabase("myDB", "1.0", "Example Database", 2*1024*1024);
db.transaction(function(tx) {
tx.executeSql("drop table if exists users");
tx.executeSql("create table users (id unique, name)");
tx.executeSql("insert into users (id, name) values (?, ?)", [1, "Kevin"]);
});
main.html:
var db = window.openDatabase("myDB", "1.0", "Example Database", 2*1024*1024);
db.transaction(function(tx) {
tx.executeSql("select * from users", [], function(tx, results) {
for(i=0; i<results.rows.length; i++) {
var u = {
id: results.rows.item(i).id,
name: results.rows.item(i).name,
}
console.log(u); //Nothing gets returned. Database in Resources tab is empty; no users!
}
});
});
The database I created in index.html shows up, but the User data I entered isn't there. I'm using the default Play! development web server. This problem does not occur when i'm using LightTPD, but then of course I can't access my Play! application DB due to Access-Control-Origin stuff.
I think your are getting to the main.html before the inserts can execute. Remember that WebSQL API is asynchronous, so when your code sends the transaction to drop/create/insert your app won't wait and goes straight for the main.html (if your are not using the callback to change the page).
What you have to do is send the transaction and wait for the callback (onSuccessSql) to change to the main.html. here is an example:
db.transaction(function(tx){
tx.executeSql( "insert into users (id, name)...", onSuccessSql, onError)},
onError, onReadyTransaction);
function onReadyTransaction( ){
console.log( 'Transaction completed' )
}
function onSuccessSql( tx, results ){
//go to main.html()
}
function onError( err ){
console.log( err )
}

Accessing pre-populated table on Android, getting error "No such table: TableName"

I have a prepopulated database that resides in my assets folder and is copied to my /data/data/com.package/database folder when downloaded to the emulator. I am trying to access this database via Phonegap sql calls. I have checked that the table is correctly being ported to the emulator and all of the data is correct. I keep getting an error of table not found however. I am pretty new to app dev so this could be an easy fix. Thanks.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("careerDB.db", "", "Career DB", 60416);
var careers;
errorHandler = function(){
$('#careerList').append('Error!');
}
db.transaction(getCareerList);
function getCareerList(transaction){
transaction.executeSql('SELECT * FROM Careers',[], function(transaction, results) {
$('#careerList li').remove();
for(var i=0;i<results.rows.length;i++){
var row = results.rows.item(i);
$('#careerList').append('<li><h4>' + row['career'] + '</h4></li>');
}
$('#careerList').listview('refresh');
},errorHandler);
}
}

SQLite database in Javascript locally

I'm using a PhoneGap project on XCode.
I am trying to connect to a SQLite databse by using Javascript.
I have made a file "myDatabase.sqlite" in an SQLite tool. Now my question is how do I open that database in my code? Right now I'm using the following code:
var db;
var shortName = 'myDatabase';
var version = '1.0';
var displayName = 'myDatabase';
var maxSize = 65535;
db = openDatabase(shortName, version, displayName,maxSize);
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM User;', [],
function(transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
alert(row.ID);
}
}
}, errorHandler);
}, errorHandler, nullHandler);
The problem is that the database is empty because when i run it it gives the error 'No such table'.
I think it created a new database named "myDatabase" and thats why it has no tables.
Does anyone know how I can open my file with all the tables in it?
Thanks!
This script will help you:
<script type="text/javascript">
function createDatabase(){
try{
if(window.openDatabase){
var shortName = 'db_xyz';
var version = '1.0';
var displayName = 'Display Information';
var maxSize = 65536; // in bytes
db = openDatabase(shortName, version, displayName, maxSize);
}
}catch(e){
alert(e);
}
}
function executeQuery($query,callback){
try{
if(window.openDatabase){
db.transaction(
function(tx){
tx.executeSql($query,[],function(tx,result){
if(typeof(callback) == "function"){
callback(result);
}else{
if(callback != undefined){
eval(callback+"(result)");
}
}
},function(tx,error){});
});
return rslt;
}
}catch(e){}
}
function createTable(){
var sql = 'drop table image';
executeQuery(sql);
var sqlC = 'CREATE TABLE image (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, image BLOB )';
executeQuery(sqlC);
}
function insertValue(){
var img = document.getElementById('image');
var sql = 'insert into image (name,image) VALUES ("sujeet","'+img+'")';
executeQuery(sql,function(results){alert(results)});
}
<input type="button" name='create' onClick="createDatabase()" value='Create Database'>
<input type="button" name='create' onClick="createTable()" value='create table'>
<input type="button" name='insert' onClick="insertValue()" value='Insert value'>
<input type="button" name='select' onClick="showTable()" value='show table'>
<input type="file" id="image" >
<div result></div>
</script>
To download the code go visit url:
http://blog.developeronhire.com/create-sqlite-table-insert-into-sqlite-table/
myDatabase and myDatabase.sqlite are 2 different filenames, update your code to reference the correct filename with extension.
SQLite does automatically create a new empty database if you try to open a database that doesn't exist.
In my sqlite code I am using three js file for controlling sqlite one for debugging purpose, one for executing querys and another one for initilize the database and create basic tables.
debug.js
startup.js
query.js
Reference URL is http://allinworld99.blogspot.in/2016/04/sqlite-first-setup.html
startup.js
var CreateTb1 = "CREATE TABLE IF NOT EXISTS tbl1(ID INTEGER PRIMARY KEY AUTOINCREMENT, CreatedDate TEXT,LastModifiedDate TEXT, Name TEXT)";
var CreateTb2 = "CREATE TABLE IF NOT EXISTS tbl2(ID INTEGER PRIMARY KEY AUTOINCREMENT, CreatedDate TEXT,LastModifiedDate TEXT,Mark INTEGER)";
var DefaultInsert = "INSERT INTO tbl1(CreatedDate,Name) select '" + new Date() + "','Merbin Joe' WHERE NOT EXISTS(select * from tbl1)";
var db = openDatabase("TestDB", "1.0", "Testing Purpose", 200000); // Open SQLite Database
$(window).load(function()
{
initDatabase();
});
function createTable() // Function for Create Table in SQLite.
{
db.transaction(function(tx)
{
tx.executeSql(CreateTb1, [], tblonsucc, tblonError);
tx.executeSql(CreateTb2, [], tblonsucc, tblonError);
insertquery(DefaultSettingInsert, defaultsuccess);
}, tranonError, tranonSucc);
}
function initDatabase() // Function Call When Page is ready.
{
try
{
if (!window.openDatabase) // Check browser is supported SQLite or not.
{
alert('Databases are not supported in your device');
}
else
{
createTable(); // If supported then call Function for create table in SQLite
}
}
catch (e)
{
if (e == 2)
{
// Version number mismatch.
console.log("Invalid database version.");
}
else
{
console.log("Unknown error " + e + ".");
}
return;
}
}
debug.js
function tblonsucc()
{
console.info("Your table created successfully");
}
function tblonError()
{
console.error("Error while creating the tables");
}
function tranonError(err)
{
console.error("Error processing SQL: " + err.code);
}
function tranonSucc()
{
console.info("Transaction Success");
}
query.js
function insertquery(query, succ_fun)
{
db.transaction(function(tx)
{
tx.executeSql(query, [], eval(succ_fun), insertonError);
});
}
function deletedata(query, succ_fun)
{
db.transaction(function(tx)
{
tx.executeSql(query, [], eval(succ_fun), deleteonError);
});
}
function updatedata(query, succ_fun)
{
db.transaction(function(tx)
{
tx.executeSql(query, [], eval(succ_fun), updateonError);
});
}
function selectitems(query, succ_fun) // Function For Retrive data from Database Display records as list
{
db.transaction(function(tx)
{
tx.executeSql(query, [], function(tx, result)
{
eval(succ_fun)(result.rows);
});
});
}
I had same problem and I found out that you cannot use your sqlite db like this.
I used chrome and I found out that Chrome stores DBs in "C:\Users\%USERNAME%\AppData\Local\Google\Chrome\User Data\Default\databases".
There is a Databases.db that Chrome uses for managing DBs.
If you want to use your db you should add a record into Databases.db and put your file in "file__0" directory and rename it (your db file) to the id that is assigned to that record.

Categories