Mouhamad Ounayssi Mouhamad Ounayssi - 14 days ago 7
Android Question

Phonegap 3.5.0 Cordova File API Error: cannot read property 'dataDirectory' of undefined

We have to build an application for iOS and Android using PhoneGap Build and Apache Cordova.
The Phonegap version is 3.5.0. and we want to update the application when an internet connection is available. So we need to download some images files from online server to local file system into the application(iOS and Android).
Here is the example JavaScript code used:

try{
//The directory to store data
var store;
//Used for status updates
var $status;
//URL of our asset
var assetURL = "https://raw.githubusercontent.com/cfjedimaster/Cordova-Examples/master/readme.md";
//File name of our important data file we didn't ship with the app
var fileName = "mydatafile.txt";
//////////////////////
alert("Checking for data file.");
//Check for the file.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
/////////////////////////////
} catch(e){
alert(e.message);
}

function downloadAsset() {
var fileTransfer = new FileTransfer();
alert("About to start transfer");
fileTransfer.download(assetURL, store + fileName,
function(entry) {
alert("Success!");
appStart();
},
function(err) {
alert("Error!");
console.dir(err);
alert(err);
});
}

//I'm only called when the file exists or has been downloaded.
function appStart() {
// $status.innerHTML = "App ready!";
alert( "App ready!");
}

function onFileSystemSuccess() {
try{
store = cordova.file.dataDirectory;
//Check for the file.
window.resolveLocalFileSystemURL(store + fileName, appStart, downloadAsset);
} catch(e){
alert(e.message);
}
}

function onError(){
alert('error');
}


When launching the application, the result is 2 alerts:


  • Cannot read property 'dataDirectory' of undefined
    // alert(e.message);

  • Error
    // alert('Error');


Answer

Ok, we found the problem! Inside the app, we have included the cordova js file using the downloaded version of cordova plugin, which included in the js folder of the app. So instead of the below:

<script type="text/javascript" src="js/cordova.js"></script> 

it's recommended to type:

<script type="text/javascript" src="cordova.js"></script> 

And Phongap will add the cordova file itself.

Comments