Search code examples
androidappceleratorexport-to-csvappcelerator-titanium

Save data in sd card using appcelerator for android 6 and above


I try to save data(.csv) in sd card using my mobile application develop using appcelerator.

For android 5 and below it success the csv can store in sd card but in android 6 and 7 I cant find the file.

I'm using this code : Ti.Filesystem.externalStorageDirectory from http://docs.appcelerator.com/platform/latest/#!/guide/Filesystem_Access_and_Storage

the code is

exports.exportCsvData = function(input)
{
var rowTxt = "";
for(var i=0;i < input.length; i++){ 
    for(var j = 0; j < input[i].length; j++){ 
        rowTxt += '"' + input[i][j] + '"';

        if(j < (input[i].length-1))
        {
            rowTxt += ',';
        }
    }
    rowTxt += '\n';// adding new line at end of row
}

// creating output file in application data directory
// option 1  
   var outputFile = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory,'output.csv');

outputFile.write(rowTxt); 


if(outputFile.exists){
    alert("CSV generated!!!");
}

return outputFile.nativePath; 
};

I also give permission to save file in sd card :

<manifest>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>

can help me to solve this problem.


Solution

  • In Android 6.0 and above you should ask for certain permissions during runtime. You can check the "Permissions" section here:

    http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Android

    There is an example how you can do that. More detailed explanation on Android side you can find here:

    https://developer.android.com/training/permissions/requesting.html