Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

android - Writing and reading file in phonegap

I tried writing/reading a file in phonegap+android, here is the set up:

$(document).ready(function() {
    document.addEventListener("deviceready", deviceready, true);

    $(document).bind("deviceready", function(){
    //writeFile();
    //readFile();
    });
});

function deviceready() {
    writeFile();
    readFile();
}

// This is just to do this.
function readFile() {
    var d = navigator.file.read('/sdcard/foo.xml', success(), fail());
    console.warn(d);
}

function writeFile() {
    navigator.file.write('/sdcard/foo.xml', "This is a test of writing to a file",
            success(), fail());
}

But on the emulator for Android 2.2, I got the following error message:

08-06 14:21:29.428: INFO/Web Console(936): Error in success callback: Network Status1 = TypeError: Result of expression 'navigator.file' [undefined] is not an object. at file:///android_asset/www/phonegap.0.9.6.js:649

What could be missing and what could be tried?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This also works in Android 2.2. You call the load(); function from body's onLoad, and writeFileFromSDCard(string) from some button's onClick, passing as parameter the string you want to write in the file.

<script type="text/javascript" charset="utf-8">

 // Event listener    
 function load() {
    document.addEventListener('deviceready', init, false);
 }

 // Called when device is ready - Do nothing 
   function init() {
 }      

// Called to write file to card
   function writeFileFromSDCard(param) {

    var writer = new FileWriter("/sdcard/write.txt");
    writer.write(param + "
", false);              
    alert("file Written to SD Card");
}

</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...