Cordova : How to check if File API works? - android

As I am having real troubles debugging an app in Android / iOs, can someone tell me some simple test to check if Cordova File API is loaded and works ?
Something like:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if(fileAPI){ // what can I test there ?
alert('File API is OK');
}
}

Try to request the FileSystem
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
alert("it works");
}, function (e) {
alert("it doesn't work");
});

Related

navigator.contacts is undefined

I want to view all contacts but the navigator.contacts is undefined.
cordova plugin add cordova-plugin-contacts
cordova build android
$(document).ready(function(){
$(document).on('deviceready', function(){
alert('something');
}, false); //it doesn't even alert something;
console.log(navigator.contacts);
});
I have take it out of document ready either. NO RESULT :(
Someone said the problem can be fixed by removing and adding platform android and adding plugin again, however it didn't!
I have also put the script tag to the end, in order that the page to be loaded then run the scripts.
I tried this code sometime back in my project and it worked:
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
$('#contact').click( function()
{
try {
var contact = navigator.contacts.create({"displayName": "CordovaUser"});
var phoneNumbers = [];
phoneNumbers[0] = new ContactField('work', '212-555-1234', false);
phoneNumbers[1] = new ContactField('mobile', '917-555-5432', true); // preferred number
phoneNumbers[2] = new ContactField('home', '203-555-7890', false);
contact.phoneNumbers = phoneNumbers;
contact.save();
alert("Contact created successfully");
}
catch(err) {
alert("Plugin Error - " + err.message);
}
});
}

Cordova Contacts Plugin not always showing Contact List

I have the contacts plugin in my app and on one test device (iPhone 5, iOS 9.02) the contact list does not show. And when I do a search, nothing appears. I get no error messages. On some of my other devices like some Android or iOS 8.x devices it does work. This particular problem device has 1200 contacts. Anyone have some suggestions on how to fix? I'll paste the relevant part of my code. Although maybe it is more of a configuration issue?
$scope.getAllContacts = function(searchQuery) {
try {
var opts = { //search options
filter: searchQuery, // 'Bob'
multiple: true, // Yes, return any contact that matches criteria
fields: ['displayName', 'name']
};
if (ionic.Platform.isAndroid()) {
opts.hasPhoneNumber = true; //hasPhoneNumber only works for android.
};
$ionicLoading.show();
$cordovaContacts.find(opts).then(function(contactsFound) {
$scope.contacts = contactsFound;
$ionicLoading.hide();
});
} catch (err) {
alert(err.message);
}
};
$scope.getAllContacts("Ak");
Hi use this to save all contacts in sdcard and display. (default Cordova contacts and file plugin)
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
navigator.contacts.find(["*"], function(contacts) {
// alert("contacts.length = " + contacts.length);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile("contacts.json", {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(){
// Success Contacts saved to sdcard as a contacts.json file
// Now get and read the json file
var path = fileSystem.root.getFile("contacts.json", {create:false},gotFileEntry, fail);
// jquery
$.getJSON(path, function (data) {
user = data;
$.each(user, function (index, user) {
var all_item = '<p id="'+user.id+'">'+user.displayName+'</p>';
$('#allcontacts').append(all_item);
});
});
};
writer.write(JSON.stringify(contacts));
}, onError);
}, onError);
}, onError);
}, onError,{"multiple": true});}
function onError(){
alert("Error");
}
You may use navigator.contacts.find, and see if this works in your phone.
For more details
https://github.com/apache/cordova-plugin-contacts

XDK built app not working

I searched a lot, but I couldn't find an answer. I use Intel XDK for Cordova/Phonegap development.
Everything is ok (emulate tabs, debug, etc.). I went to Build tab and get my .apk, moved it to SD card and installed, but, it doesn't work when run.
If I build my source with Phonegap Build (Online), everything works fine.
My JS code:
<script type="text/javascript">
document.addEventListener("backbutton", function(){ return; }, true);
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
//navigator.splashscreen.hide();
var server = 'http://xxxxxx/index.php?';
var user_uuid = device.uuid;
$( document ).ready
(
function()
{
$("#main_content").css("top", "50%");
$("#main_content").css("margin-top", "-"+($("#main_content").height()/2)+"px");
$("#main_content").show();
$("#big_img_load").attr("src", "img/ajax-loader.gif");
var xinv = setInterval
(
function()
{
var networkState = navigator.connection.type;
if(networkState.trim() == 'none')
$("#no_internet").show();
else
{
$.post
(
server+"do=boot",{useruuid: user_uuid},function(data)
{
if(data.trim() != "ok")
window.location = "error.html";
else
{
clearInterval(xinv);
window.location = "app.html";
}
}
);
}
},
1000
);
}
);
};
</script>
It remains in loading: No internet check, no POST to the URL, nothing.
Where is the problem? Why only build from XDK is not working?
My suspicion is you do not have the domain whitelisting section in the build settings set correctly for your app. See this article for some hints: https://software.intel.com/en-us/articles/cordova-cli-412-domain-whitelisting-with-intel-xdk-for-ajax-and-launching-external-apps and make sure to build your app using Crosswalk, not Android, for best results on Android devices.

Get Device absolute path in phonegap?

I'm using Phonegap 3.3.0, earlier i used 2.5.0 where entry.fullPath will give the Device full path.
These paths would typically look like
/var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
/storage/emulated/0/path/to/file (Android)
since that method is deprecated am using entry.toURL() method to get the path.This method will now return filesystem URLs of the form
cdvfile://localhost/persistent/path/to/file
In My application, am passing the URL to Native function and from native am opening a file. But If I pass the path to Native, iOS could not able to detect the file. The same If i hardcode the Absolute path, application detects the file.
How to use the fileSystem URL to access the file in native or any other method to get the device absolute path ?
Thanks in advance.
The toURL() method or the nativeURL attribute should return the result wanted:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
console.log("fileSystem.root.toURL()="+fileSystem.root.toURL());
console.log("fileSystem.root.toInternalURL()="+fileSystem.root.toInternalURL());
console.log("fileSystem.root.nativeURL="+fileSystem.root.nativeURL);
}, function(){
alert("fails!");
});
Using cordova 3.5, the output in iPad simulator is:
fileSystem.root.toURL()=file:///Users/myuser/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/1717CB5F-4032-45C7-8CA2-342502447F36/Documents/
fileSystem.root.toInternalURL()=cdvfile://localhost/persistent/
fileSystem.root.nativeURL=file:///Users/myuser/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/1717CB5F-4032-45C7-8CA2-342502447F36/Documents/
...and in Android simulator (Genymotion) is:
fileSystem.root.toURL()=file:///storage/emulated/0/
fileSystem.root.toInternalURL()=cdvfile://localhost/persistent/
fileSystem.root.nativeURL=file:///storage/emulated/0/
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("device is ready");
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function fail() {
console.log("failed to get filesystem");
}
function gotFS(fileSystem) {
console.log("got filesystem");
// save the file system for later access
console.log(fileSystem.root.fullPath);
window.rootFS = fileSystem.root;
}
function downloadImage(url, fileName){
var ft = new FileTransfer();
ft.download(
url,
window.rootFS.fullPath + "/" + fileName,
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error" + error.code);
}
);
}
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
alert("entered gotFS: " + fileSystem.root.toURL);
}

Phonegap: Can you create 2 writers for a single file?

I've recently started using phonegap to develop on android. I ran into this problem while learning the File plugin API, I was wondering if it is possible to create 2 writers for a file (on two different pages). When I tried the code below on two different pages (one writes: "This team has not been scouted" and the other writes: "This team has been scouted :)" For some reason only one will work at a time, if i run the first one first it creates the file and writes to it, but the second one won't work. Likewise, if I run the second one first it creates the file and writes to it, but the first one won't work.
<script type="text/javascript" charset="utf-8">
alert("waiting...");
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
alert("Device Ready!");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null);
}
function onRequestFileSystemSuccess(fileSystem) {
alert("Got file system!");
fileSystem.root.getDirectory("FRC_SCOUT_DATA", { create: true }, onGotDir, null);
}
function onGotDir(dataDir) {
alert("Got Directoy!");
dataDir.getFile("data_1539.txt", { create: true, exclusive: true }, onFileCreated, null);
alert("Got File!");
}
function onFileCreated(dataFile) {
dataFile.createWriter(gotFileWriter, null);
}
function gotFileWriter(writer) {
writer.write("This team has been scouted :)");
}
</script>
(code on second page is essentially the same with the exception of the message thats being written to the text file)
You have kept exclusive: true .So it will give you an error if file already exist try setting it to false.Check this out
So change your code from this
dataDir.getFile("data_1539.txt", { create: true, exclusive: true }, onFileCreated, null);
to
dataDir.getFile("data_1539.txt", { create: true, exclusive: false}, onFileCreated, fail);
function fail(error) {
console.log(error.code);
}

Categories

Resources