Adding record using Indexed DB in Cordova project - android

I've a problem adding a record from a form.
When I do clic in a button call to function "save":
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
var dataBase = null;
function save() {
dataBase = indexedDB.open("bbdd", 1);
dataBase.onupgradeneeded = function (e) {
active = dataBase.result;
};
dataBase.onsuccess = function (e) {
console.log('Database loaded!');
var active = dataBase.result;
var data = active.transaction(["docs"], "readwrite");
var object = data.objectStore("docs");
var request = object.put({
idDoc: document.querySelector("#idDoc").value,
name: document.querySelector("#name").value,
});
request.onerror = function (e) {
alert(request.error.name + '\n\n' + request.error.message);
};
data.oncomplete = function (e) {
idDoc: document.querySelector("#idDoc").value = '';
name: document.querySelector("#name").value ='';
};
}
dataBase.onerror = function (e) {
console.log('Error loading database');
};
}
Ok. I testing in Chrome and Firefox (Windows XP) and works fine. Data are added to database and fields are cleared.
Now, I built cordova project and run it in a Nexus 5 (Android 5.0.1) with:
cordova run android --devices="myId"
In Nexus 5 donesn't work. When I do click in the button the mobile phone does nothing. Data aren't added to database and fields aren't cleared.
What am I doing wrong?

I have this problem, too. There seems to be a bug on Android 5.0.1 related to the browser storage. This problem happens with localStorage, webSQL and indexDB.
A lot of people are experiencing this: Android 5.0.1 localstorage not persistent.
I made a simple app just for testing. I open the app and I just simply do (I added the code when onDeviceReady - when cordova is loaded):
var a = window.localStorage.getItem('test');
alert(a); //will give you undefined first time
if (!a) {
window.localStorage.setItem('test','12345678');
alert(windows.localStorage.getItem('test');
//this will display 12345678 from localstorage evertime
}
If you close the app after 2 or 3 seconds (force-closing the app) and re-open it, the value of test from localstorage is still undefined. You can do this for 10 times and you will get undefined every time. If you wait 10 or 12 seconds after you open the app and get the alerts, you will notice that after restarting the app (force restart), the data is there and localStorage works correctly.
I tested this on Android 5.0.1 and I used cordova 3.6.3, cordova 4.0, cordova 5.0. I did the same test on a tablet with Android 4.4.2 and the localStorage is set correctly.

Related

Protractor's waitForAngular() fails on angular-webapp (appium/chrome on real device)

I'm (newly) using protractor to run e2e cucumber tests.
I got a web-app which is angularJS based. I'm using appium to remotely run the test on a real android device. Here are the versions i'm using :
windows8.1
protractor#1.3.1 (with submodule selenium-webdriver#2.43.5)
appium#1.3.0beta1
android device with 4.4.4
my protractor configuration (extracts), corresponding to https://github.com/angular/protractor/blob/master/docs/browser-setup.md:
currentDeviceUDID = (...);
var appToTestURL = 'http://my.website.com:9000/app/index.html';
exports.config = {
seleniumAddress: 'http://localhost:4723/wd/hub';
chromeOnly: false,
specs: ['features/sample.feature'],
capabilities: {
browserName: 'chrome',
'appium-version': '1.0',
platformName: 'Android',
platformVersion: '4.4.4',
udid: currentDeviceUDID
},
baseUrl: appToTestURL
framework: 'cucumber',
cucumberOpts: {
require: 'features/stepDefinitionsSample.js',
tags: '#dev',
format: 'progress'
},
// configuring wd in onPrepare
onPrepare: function () {
var wd = require('wd'),
protractor = require('protractor'),
wdBridge = require('wd-bridge')(protractor, wd);
wdBridge.initFromProtractor(exports.config);
},
allScriptsTimeout: 30000,
getPageTimeout: 30000
};
As you can see, i have replaced the protractor's webdriver url with the appium webdriver. i start the appium from commandline with "appium &", then i run the test with "protactor cucumbertest.conf"
The phone opens chrome browser and navigates to the url i give it with "browser.get(url)"
the problem is the following:
the call waitForAngular(), which is asynchronously waiting for the website to load and on all open http request (as far as i understand), is not executed sucessfully on the phone. the phone does not react to the call, and the webdriver proxy returns a 500.
Corresponding to https://github.com/angular/protractor/issues/1358, i understood that the waitForAngular() function is mixed in protractor into the calls
['getCurrentUrl', 'getPageSource', 'getTitle'];
Behind waitForAngular() in the file protractor.js is the function below, which is proxied to the phone:
functions.waitForAngular = function(selector, callback) {
var el = document.querySelector(selector);
try {
if (angular.getTestability) {
angular.getTestability(el).whenStable(callback);
} else {
angular.element(el).injector().get('$browser').
notifyWhenNoOutstandingRequests(callback);
}
} catch (e) {
callback(e);
}
};
Additional information: when i stimulate an error on the webdriver (browser) object, the error message points to the chromedriver.exe inside the protractor directory. i dont understand why the error is not from appium's chromedriver
so tldr;
without the successful call waitForAngular, i cannot (stable or at all) access elements on the page on the phone, so not testing. maybe im misunderstanding some fundamental configuration detail here, all hints are welcome.
edit: added appium server logs here: http://pastebin.com/vqBGUdXH
I assume i have identified the problem. Appium and Protractor work fine.
My angularJS app causes the issue. It uses $timeout for polling (im forced on angular 1.07 which has no $interval). This causes protractor to expect the page to be still in the loading stage and not finished. Therefore the function call waitForAngular() never returns and the test timeouts after the specified timeout-timespan.
This behaviour is expected and known, also documented (better read doc first ;) ) at http://angular.github.io/protractor/#/timeouts
The doc suggests the following for continuous polling: replace $timeout with $interval:
If your application continuously polls $timeout or $http, it will never be registered as completely loaded. You should use the $interval service (interval.js) for anything that polls continuously (introduced in Angular 1.2rc3).
For now, i fixed the issue another way: disable the built-in angular sync and manually sync
this.Before(function(next){
ptor = protractor.getInstance();
ptor.ignoreSynchronization = true; //disables waitForangular()
next();
});
Sync method 1:
//at a testcase, wait for an element to be visible with a promise/then
browser.wait(function () {
element.all(by.css('.myCssClass')).then(function (items) {
items[0].getText().then(function (text) {
console.log(text);
});
});
return true;
}
Sync method 2 :
// "eventually" (chai-as-promised) internally uses "promise" (and therefore acts like "then")
browser.get(url);
expect(browser.getTitle()).to.eventually.equal("connect me").and.notify(next);

Worklight 6.1 JSONStore call WL.JSONStore.init hangs in Android

I meet problem in JSONStore init function in Android. It will hang for about 10 minutes until then the JSONStore gives me the init result callback. This did occur only in Android and iPhone works fine. I can give the reproduce procedure:
Install my app in a 'clean' Android, which has not install the app before.
Successfully init the JSONStore by my arguemnts (I will attach the code below).
Then I re-install my app, note that I did't uninstall it but just replace it with a new build.
After replace I'm using the same auth try to init JSONStore, but it hangs....(Maybe will give the result callback at 10 minutes or longer, no error handlers trigger).
If a kill the app and re-launch it, then this time the JSONStore init very fast and works fine
I debug the App with inspect and I'm sure this is the problem that WL.JSONStore.init didn't give me result callback that hangs app. I don't know the reason why the first time need to consume so much time. Anyone meet the same issue as me?
var options = {password:pscd,localKeyGen:true};
var promise =
WL.JSONStore.init(data_collection, options).then(function(){
console.info("init json store successfully!");
return true;
}).fail(function (errorObject) {
console.info("init json store failed!" + errorObject);
return false;
});
return promise;
I just tried out the following code in the same 6.1 build that you have, and it is working fine for me on both the Android Emulator and a Nexus 4:
var data_collection = {people : {
searchFields : {name : 'string', age : 'integer'}
}
};
var pscd = "samplepassword";
var options = {password:pscd,localKeyGen:true};
var promise =
WL.JSONStore.init(data_collection, options).then(function(){
alert("init json store successfully!");
return true;
}).fail(function (errorObject) {
alert("init json store failed!" + errorObject);
return false;
});
return promise;
The only thing that might be different to your code is what your password or your data_collection variables are. Could you add more details regarding what data_collection is?

Phonegap WP7 app not perform any functionality

I am working on Cordova hybrid mobile app currently am doing in android app it runs fine now when i make same app for window phone it is not perform any functionality.
for make WP8 I follow this link after that i copy my all file of www folder to new generated www in Visual Studio project.
But when i ran app it just shows its first page only and not performing any functionality.
So what steps did i miss ?
On the click of button I call following function
$('#contactBackupBtn').on('click',function(){
$('#p2').append("Going to be backup");
sm_sync.backupAllTheContacts(function(){
$('#p4').append("After Contact Backup Function Finished ");
});
});
From above function it calls the following one
backupAllTheContacts:function(callback) {
$('#p3').append("IN backupAllTheContacts");
navigator.contacts.find(["*"], function(contacts) {
$('#p3').append("IN Contact Success");
callback();
}, sm_sync.onError, {"multiple": true});
}
onError:function(error) {
$('#p1').empty();
$('#p1').append(error.code);
$('#p1').append(error.message);
}
When i execute it, it shows this message IN backupAllTheContacts and ths Going to be backup but not showing any success or error messages. what should i do to make it run.
(This is a small part of my app it is runnng perfact in Android Emulator but not n windows
I need help i am stuck here)
use console.log is not support in windows phone so use this and use localStorage like this. try to run on deviceready
document.addEventListener("deviceready", function () {
/* This is for Console.log support in WP */
if (typeof window.console == "undefined") {
window.console = {
log: function (str) {
window.external.Notify(str);
}
};
}
var key0;
/* manage localstorage this way */
if (typeof (window.localStorage) !== "undefined") {
localStorage.setItem('lastname', "Smith");
localStorage.firstname = "One";
if (localStorage.getItem('objectKey1') != null || localStorage.getItem('objectKey1') != undefined) {
key0 = window.localStorage.getItem('objectKey1');
}
}
},false);
When i build my WP8 app i ran into somewhat an issue same as this. it's because of the jQuery i used. Then i updated my jQuery to the latest and its all started working fine.
Please check the jQuery documentation and the version you are using. Or you just put up your code in here so that we can have a closer look.
"But when i ran app it just shows its first page only and not performing any functionality.
So what steps did i miss ?"
Without the code how can we say what steps did you missed ???

Phonegap - Local storage not working - Android

I'm using Local Storage to pass values between pages in order to create a scroll to effect (user clicks link and is scrolled to particular part of the page based on ID)
I was previously using cookies but that didn't seem to work on Android, I read that local storage was supported so switched over to that. It works completely fine when in the browser but as soon as its packaged as a native app I lose all functionality? The API states that it should be supported, any ideas?
Here's my code:
Base URL:
var storage = window.localStorage;
$("a.scroll_link").click(function(event) {
event.preventDefault();
var value = $(this).attr("id");
storage.setItem("key",value);
console.log(value);
window.location=$(this).attr("href");
});
Receiving URL:
$(function () {
var value = window.localStorage.getItem("key");
if (value != "" && value != "undefined" && value != null) {
var storage = window.localStorage;
storage.setItem("key",value);
var scroll_type = "";
if ($.browser.webkit) {
scroll_type = "body";
} else {
scroll_type = "html";
}
$(scroll_type)
.stop()
.animate({
//get top-position of target-element and set it as scroll target
scrollTop: ($("#" + value).offset().top - 25)
//scrolldelay: 1.5 seconds
}, {
duration: 1500,
complete: function () {
storage.removeItem("key");
},
});
}
});
The code works fine in the browser just not natively, any ideas?
Thanks,
Use document.addEventListener("deviceready", onDeviceReady, false) instead of $(function(){...}
http://docs.phonegap.com/en/2.5.0/cordova_events_events.md.html#deviceready
1.Glad to know you solve your first problem. As gmh04 say, I think you should replace your init event with 'deviceready' which is triggered when the app start running.
2.
You mean window.localStorage.getItem("key") return null in Receiving URL?
I do not exactly encounter a problem as what you describe. However, you may try to move your code in receiving url to the same page of base url. I have tried for times and be very sure that the localStorage will work in the same page.
I would like add that there's a bug on the 2.6.0 version of cordova.js that make localStorage don't work on Android:
https://issues.apache.org/jira/browse/CB-3063
On the 2.5.0 version it works perfectly, and it is already fix on the 2.7.0 rc.

query string is not working in phonegap 2.1.0 for android 4.0

I have developed android phonegap application using phonegap 1.9.0.Its was working fine in android 2.2 and 4.0.Later i changed the phonegap version and currently i am using phonegap 2.1.0.Its working fine in android 2.2 but in android 4.0 i cannot able to navigate from one page to another,while passing the value as query string.
Here is my code:
function onClick()
{
var id="2";
window.open("index2.html?id="+id);
}
Index2.html:
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++)
{
var pair = vars[i].split("=");
if (pair[0] == variable)
{
return pair[1];
}
}
}
Get the value in index2.html as
var id=getQueryVariable("id");
Please help me.Thanks in Advance.
I switched to 2.0.0 specifically due to a bug with query string in prev versions and android 4. Gave the 2.1.0 a try and it is broken again. Why I wanted to upgrade? Because 2.0.0 has camera issues like user takes a pic that is supposed to show on a web page and the success function or fail are not fired. Tried with 10, 50 and 100 % picture quality. It works on my phone but not on others with same ver Android.

Categories

Resources