Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a file on Android? (Firemonkey)

How can I save a file locally on an Android device, using Delphi (XE5, Firemonkey)?

Something as simple as

  Memo.Lines.SaveToFile('test.txt')

does not seem to work. It results in the following error message:

"Cannot create file "/test.txt". Not a directory."

like image 300
Reinier Avatar asked Sep 17 '13 19:09

Reinier


4 Answers

According to the document Creating an Android App, get the documents path like this:

System.IOUtils.TPath.GetDocumentsPath + System.SysUtils.PathDelim + 'myfile';
like image 160
Marcus Adams Avatar answered Nov 13 '22 13:11

Marcus Adams


Instead of using System.SysUtils.PathDelim, you may use

System.IOUtils.TPath.Combine(System.IOUtils.tpath.getdocumentspath,'test.txt');

Combine chooses between the windows \ and the Linux /

System.IOUtils must be used in this line instead of setup in the uses clause because there are probably more Tpath initials.

like image 42
user3015173 Avatar answered Nov 13 '22 14:11

user3015173


GetHomePath, return a string with the path. -> 'data/data//files'

You can to use:

Memo.Lines.SaveToFile(format('%s/test.txt', [GetHomePath]));

Or this form

Memo.Lines.SaveToFile(GetHomePath + '/test.txt');
like image 2
Juan Avatar answered Nov 13 '22 14:11

Juan


on my device (and presumably all android devices?) GetHomePath incorrectly gives me /storage/emulated/0/... whereas I need /storage/sdcard0/... to get to the storage visible in Windows Explorer via USB.

so the full path to my files may be '/storage/sdcard0/Android/data/com.embarcadero.(my app name)/files/'

Presumably if you have a plug in SD card this might be sdcard1 or whatever.

You can list the contents of your device storage folder with code like this

  P := '/storage/';
  if (FindFirst(P + '*', faAnyFile, Sr) = 0) then
  repeat
    Memo1.Lines.Add(Sr.Name);
  until (FindNext(Sr) <> 0);
  FindClose(Sr);

On my device this gives me:

sdcard0 usb emulated

then change S when you want to explore subfolders

Note that the files folder gets emptied each time you recompile and deploy.

like image 2
Leslie Kaye Avatar answered Nov 13 '22 13:11

Leslie Kaye