FIle API - Phonegap? - android

Can anybody explain how to list a folder of files on a page using the Phonegap File API for Android?
I would like to list all .mp3 files if possible, but have read through all the phonegap docs (http://docs.phonegap.com/en/1.0.0/phonegap_file_file.md.html) and cant figure it out at all!

it is a bit of a pain in the #$$ but doable. Start with this code:
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory("Music", {create: false, exclusive: false}, getDirSuccess, fail);
}
function getDirSuccess(dirEntry) {
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess,fail);
}
function readerSuccess(entries) {
var i;
for (i=0; i<entries.length; i++) {
// Assuming everything in the Music directory is an mp3, go nuts
// otherwise check entries[i].name to see if it ends with .mp3
}
}
I'm writing all this example code outside of an IDE so there may be bugs but that should get you going.

Paul, did you add a fail() function? That will be required in Simon's example code. The api docs example has:
function fail(evt) {
console.log(evt.target.error.code);
}

You could also save one step in Simon's code if you just wanted a proof of concept, since fileSystem.root is already a dirEntry (and it saves you the potentially buggy step of having to use a directory name such as "Music" which might or might not be there):
function onFileSystemSuccess(fileSystem) {
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess,fail);
}
function readerSuccess(entries) {
var i;.......
which works for me.
However, what I get are the contents of the root directory of the app, apparently, my app being called be.qan.blaActivity, so, if I ask it for fileSystem.root.name it tells me "be.qan" and the fileSystem.root.path is undefined. Thus, my question here would be: how can I break out of this sandbox, if that is indeed what I am sitting in, and can I access the sd_card directories or other parts of the file system (since iOS still does not even have external storage)?
What I am getting by way of file names in readerSuccess are names such as "databases", "app_database", "cache" and "lib" which do not even show up when I do a search with Astro FileManager, so I strongly suppose they are part of a virtual file system that Cordova is creating for the app or so. Probably there is still a lot I am missing and folks more knowledgeable than I can set me straight, but that's what I am guessing so far.

Hi I use this code and it works for me .. can try it
$('#recordingList').on('pagecreate', function(event) {
generateRecordingList();
});
function generateRecordingList(){
//request for the file system
window.resolveLocalFileSystemURI("file:///sdcard/rem", onFileSystemSuccess, onError);
}
function onFileSystemSuccess(fileSystem){
alert("FileSystem success : " + fileSystem.name);
}
function onError(error){
alert(error.target.error.code);
}

Related

Cordova - Is it possible to list .bap files inside Android tablet directory "internal storage/bap"?

I'm totally new to Cordova and my current project happens to be implemented with that. I would need a way to read and list files inside a directory located at Internal storage/bap.
I've tried almost every possible way Google has given to me but without luck. If someone has any idea or could point me in the right direction, it would be really appreciated!
Edit
Managed to at least log the files with the following function, just had to be exact with the path and pass a full native path to the desired directory:
function listDir(path: string): any {
window.resolveLocalFileSystemURL(
path,
function(directory) {
var reader = directory.createReader();
reader.readEntries(
function(entries: any) {
console.log("entries inside listDir");
console.log(entries);
},
function(err: any) {
console.log(err);
}
);
},
function(err) {
console.log(err);
}
);
}

XMLHttpRequest in Cordova for android

I'm actually stuck with a problem. Building a app in Cordova, for Android. I need to download a PDF from a variable path in the server. With a documentation from Cordova said "Transition off of cordova-plugin-file-transfer", located here , I tried this:
var oReq = new XMLHttpRequest();
// Make sure you add the domain name to the Content-Security-Policy <meta> element.
oReq.open("GET", endereco, true);
// Define how you want the XHR data to come back
oReq.responseType = "blob";
oReq.onload = function (oEvent) {
var blob = oReq.response; // Note: not oReq.responseText
if (blob) {
console.log("WORKS??");
} else console.error('we didnt get an XHR response!');
};
oReq.send(null);
where "endereco" is a variable where I store the pdf path. So, I'm testing and testing, but maybe someone got some pointers in how to implement this. Right now it just log "WORKS??", so I actually connected successfully. But what now?
1 - so, I made a request, but the file was saved? Couldn't find nothing in my mobile. How can I save said blob in a folder, with the same name and extension from the server?
So, if someone can at least send me to some proper examples or documentation, it would help a lot. Right now I'm reading all on MDN Web Docs, but I'm fairly noob with this type of code :(
thanks in advance!
so, this is how it worked for me! Using the info from the official documentation at cordova, formerly named "cordova-plugin-file" (link), and the amazing info from this page with examples "CORDOVA FILE PLUGIN EXAMPLES" (link) it worked. It could use some cleanup and some error callbacks, but right now I can run this, and download and save an pdf to my android. Hope it helps someone! B-)
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
var fileURL;
var req = new XMLHttpRequest();
req.open("GET", endereco, true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
console.log(blob.type);
console.log("WORKS!");
console.log(fileURL);
// cordova.file.etc is where you will save the file. In this case, inside the app folder, in the main storage in Android
window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
// the 'temp.pdf' is the name you want for your file.
directoryEntry.getFile('temp.pdf', { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
// great success!
console.log('Write of file completed.');
};
fileWriter.onerror = function (e) {
// Meh - fail
console.log('Write failed');
};
fileWriter.write(blob);
} );
} );
});
};
req.send();}

How to make ionic application read in json data from .json file that is local to application

I have a Cordova app that uses the ionic framework. I have many json data files that I put in the www/json folder in my app's file tree. I am using angularJS http calls to access them.
When I test my app in chrome (using "ionic serve" in the terminal) it works fine but when I test it on an android device(nexus 5 with Android 6.0 Marshmallow) it no longer works.
Sample code
function getBookNames() {
return $http.get("..\\bookfolder\\Books.json")
.then(function (data) {//if success than do
return data.data;
}, function (reason) {// if fail than do
// maybe tell the user what happened...
});
}
I have tried adding
var path = "";
if (ionic.Platform.isAndroid()) {
path = "\\android_asset\\www\\";
}
function getBookNames() {
return $http.get(path + "..\\bookfolder\\Books.json")
.then(function (data) {//if success than do
return data.data;
}, function (reason) {// if fail than do
// maybe tell the user what happened...
});
}
when I am debugging the app on my phone I get the following error.
GET file:///android_asset/bookfolder/Books.json net::ERR_FILE_NOT_FOUND
If anyone knows what I am doing wrong or of a better way to access local .json files please let me know. Thanks!
Use slash / character, not backslash \. Also, put bookfolder inside /android_asset/www
$http
.get('/android_asset/www/bookfolder/books.json')
.then(function(response){ return response.data });

How to add sounds with JQM and IntelXDK

I am working on an app and using IntelXDK to build it. I need to play some sounds if conditions are met, first I have tried HTML5 with JS and on desketop it's working but when built, it has no sound...
First attempt - HTML5 & JS
<audio src="snd/yes.mp3" id="yes"></audio>
<audio src="snd/no.mp3" id="no"></audio>
if(condition) {
$('#yes').trigger("play");
} else {
$('#no').trigger("play");
}
Then I tried the native IntelXDK version that goes like this:
if(condition) {
intel.xdk.player.playSound("snd/yes.mp3");
} else {
intel.xdk.player.playSound("snd/no.mp3");
}
No only that it doesn't work but it also f***s up the rest of my code not allowing the popup and page change to trigger.
Does anyone know how to fix this ?
Do I need to preload the sounds before playing them?
**UPDATE
I just discovered that if I use the HTML5 Audio tags and I give links to the sounds inside my server, the sounds are working, but if I try to get the same sounds from my snd folder they won't work...why is that?
The problem is that your "root" is not where you think it is, so your "snd" directory is not being found. This problem varies, unfortunately, with each target, it is not something the XDK controls, it has to do with how Cordova apps are constructed. You can use these functions to locate the root of your files and that should help you make this work.
// getWebPath() returns the location of index.html
// getWebRoot() returns URI pointing to index.html
function getWebPath() {
"use strict" ;
var path = window.location.pathname ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return 'file://' + path ;
}
function getWebRoot() {
"use strict" ;
var path = window.location.href ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return path ;
}

Create a directory in data/data/{package_name} Phonegap Android

Is this possible? I had a look at other answers like this but I am using window.resolveLocalFileSystemURI("file:///data/data/{package_name}", onSuccess, onError);
therefore the object I get back from onSuccess callback does not have the 'root' so the following will fail:
function onSuccess(fileSystem) {
var entry=fileSystem.root;
entry.getDirectory("example", {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail);
}
because fileSystem.root is undefined.
I assume it is not currently possible in Phonegap?
Edit: I am already writing files in data/data successfully using Phonegap, in subdirectories of Files folder I created using native code, like:
Files/images
Files/videos
Files/audios
I would like to create images/my_sub_folder or videos/my_subfolder
as for me, I use plugin to write any data to system. Js only make a calls to plugins (DB, IO, Service, etc) all work with enviroment makes native logic, JS only recive data through callbacks to show it.
It's because resolveLocalFileSystemURI pass a DirectoryEntry object to the success callback and not a FileSystem object. It's like you already get fileSystem.root.

Categories

Resources