Jez D Jez D - 4 months ago 15
Android Question

Phonegap Android create file if not exists and write to it

Morning,

I am using the following to create a file on the local file system. This creates a file if it did not already exist.

function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);

}

function gotFS(fileSystem) {
fileSystem.root.getFile("test.txt", {create: true}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {
writer.onwrite = function(evt) {
alert("write success");
};
writer.write("We are testing")

}

function fail(error) {
if(error.code == 1){
alert('not found');
}
alert(error.code);
}


However, I need to write to the file ONLY if it did not already exist.
I tried using

function gotFS(fileSystem) {
fileSystem.root.getFile("test.txt", null, gotFileEntry, fail);
}

function gotFS2(fileSystem) {
alert('trying again');
fileSystem.root.getFile("test.txt", {create:true}, gotFileEntry, fail);
}

function fail(error) {

if(error.code == 1){
alert('not found');
gotFS2(fileSystem);
}
alert(error.code);
}


and then calling gotFS2 if error.code == 1
but that did nothing - it didn't even create the file when it didn't exist.

It seems that gotFS2 was not called, yet
alert('not found');
in the function fail(error) works.

What's the easiest way to do what I am trying to do?

Answer

It seems that problem is in your not saving fileSystem variable (which is in local scope in "gotFS"), so my suggestion is:

var savedFS;

function gotFS(fileSystem) {
    savedFS = fileSystem;
    fileSystem.root.getFile("test.txt", null, gotFileEntry, fail);
}

function gotFS2(fileSystem) {
    alert('trying again');
    fileSystem.root.getFile("test.txt", { create: true }, gotFileEntry, function() {});
}

function fail(error) {
    if (error.code == 1) {
        alert('not found');
        gotFS2(savedFS);
    }
    alert(error.code);
}