Reputation: 91
I am using phonegap and i want to access a file located at www/res from an android device but it's throwing NOT_FOUND_ERR... I'm sure the file it's located there and here it's the code I wrote:
onDeviceReady: function(){
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory + "www/res/myfile.txt", app.gotFile, app.fail);
},
gotFile: function(fileEntry){
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function(e) {
alert(this.result);
}
reader.readAsText(file);
});
},
fail: function(e){
console.log("Error reading");
console.log(e.code);
}
The code it's super simple yet I can't see what's wrong with it!
Upvotes: 3
Views: 4217
Reputation: 1177
The local URL cordova.file.applicationDirectory works for iOS but not Android. You will have to iterate through the cordova.file.dataDirectory until you find the /res directory as a child of the GUID-named app directory.
Try the following:
var dirEntry = function (entry) {
var dirReader = entry.createReader();
dirReader.readEntries(
function (entries) {
$.each(entries, function (n, i) {
if (i.isDirectory === true) {
if (i.nativeURL.indexOf('www/res') > -1) {
//found the target /res directory
var path = i.nativeURL + '/myfile.txt';
window.resolveLocalFileSystemURL(path, app.gotFile, app.fail);
return false; //no need to iterate more
} else {
// Recursive -- call back into this subdirectory
dirEntry(i);
}
}
});
},
function (error) {
console.log("readEntries error: " + error.code);
}
);
};
var dirError = function (error) {
console.log("getDirectory error: " + error.code);
};
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, dirEntry, dirError);
Upvotes: 2
Reputation: 981
I could try the code you have given. It works fine if you change the function name resolveLocalFileSystemURL
to resolveLocalFileSystemURI
, at least for me. You can see PhoneGap documentation
Upvotes: 1
Reputation: 981
You can try to use relative path. Of course it depends on where the code you stated in the question is located. I assume this code is inside default phonegap index.js file whose directory is 'www/js/index.js'. Relative path to txt file would be '../res/myfile.txt'.
window.resolveLocalFileSystemURL("../res/myfile.txt", app.gotFile, app.fail);
Upvotes: -1