bofanda
bofanda

Reputation: 11826

PhoneGap: File API - loading json data on click event

I've implemented code for loading json data from external file on device. The program should work like this: On click event first it will try to look into local storage file (course.txt) and if it's exist read and display it (list of titles).

HTML code:

<div data-role="page" id="page1">
    <a href="#page2" onclick="courseList()">Load Course</a></div>
</div>
<div data-role="page" id="page2">
    <p id="text" align="center"></p>
    <div id="print"></div>
</div>

JS code:

jsonString = '';
function courseList() {
    readWriteFile();
    var myData = JSON.parse(jsonString);
    if (myData != '' || myData != undefined) {
        var $list = $('#print');
        $.each(myData, function(i, item) {
            $list.html(item.title);
        });​
    } else {
        document.getElementById('text').innerHTML = 'No data in storage';
    }
}

function readWriteFile() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, onFSError);
}
function onFSSuccess(fileSystem) {
    fileSystem.root.getFile("course.txt", {create:true, exclusive:false}, gotFileEntry, onFSError);
}
//FileReader Cordova API
function gotFileEntry(fileEntry) {
    fileEntry.file(gotFile, onFSError);
}
function gotFile(file) {
    readAsText(file);
}
function readAsText(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("Read as text");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
    jsonString = reader.readAsText(file);
}
function onFSError(err) {
    console.log(err.code);
}

The result is empty considering above mentioned procedures. I can't detect my mistake. Any help would be appreciated.

Upvotes: 0

Views: 1883

Answers (2)

Jyoti Prakash
Jyoti Prakash

Reputation: 4027

This is happening because file read is happening asynchronously. Add your readAsText in onloadend.

Try to add this:

function readAsText(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("Read as text");
        console.log(evt.target.result);
        reader.readAsText(file);
        jsonString = reader.readAsText(file);
    };   
}

Upvotes: 1

最白目
最白目

Reputation: 3654

try this

function readAsText(file) {
  var reader = new FileReader();
  //asnycrhonous task has finished, fire the event:
  reader.onloadend = function(evt) {
    console.log("Read as text");
    console.log(evt.target.result);
    //assign the data to the global var
    jsonString = evt.target.result
    //keep working with jsonString here
  };
  reader.readAsText(file);    
}

Upvotes: 2

Related Questions