Phonegap Android write to sd card

Ad

Given code below if i test with Phonegap Developer in mobile, it creates a file in root of my Nexus 5 device.

// create a file writer object
function CreateFileWriter()
{
    // request the file system object
window.requestFileSystem( LocalFileSystem.PERSISTENT, 0, OnFileSystemSuccess,fail);
}

function OnFileSystemSuccess( pFileSystemObj )
{
    console.log( pFileSystemObj.name );
    console.log( pFileSystemObj.root.name );

    pFileSystemObj.root.getFile( "file_name.txt", {create: true, exclusive: false}, OnFileGetSuccess, fail);
}

function OnFileGetSuccess( pFileEntryObj )
{
    pFileEntryObj.createWriter( function(pWriterObj){ 
    gWriterObj  = pWriterObj; 
    }, fail );
}

function fail(evt)
{
    console.log(evt.target.error.code);
}

But, if I deploy the app and generate the apk. After installation in my device. The file is not created in root.

I have given permission in AndroidManifest.xml and added file plugin. Also, debugged from gapdebug. It does not shows any error. I assume the file is created somewhere else. but I need to write file on root of sdcard or internal memory.

Please Help!

Thanks,

Ad

Answer

Ad

Write file example:

var fileName = 'myfile.txt';    // your file name
var data = '...';               // your data, could be useful JSON.stringify to convert an object to JSON string
window.resolveLocalFileSystemURL( cordova.file.externalRootDirectory, function( directoryEntry ) {
    directoryEntry.getFile(fileName, { create: true }, function( fileEntry ) {
        fileEntry.createWriter( function( fileWriter ) {
            fileWriter.onwriteend = function( result ) {
                console.log( 'done.' );
            };
            fileWriter.onerror = function( error ) {
                console.log( error );
            };
            fileWriter.write( data );
        }, function( error ) { console.log( error ); } );
    }, function( error ) { console.log( error ); } );
}, function( error ) { console.log( error ); } );
Ad
source: stackoverflow.com
Ad