How and where to create files on Android with Delphi

2

In my Delphi application I'm creating a plain text file on Android using the following code:

var lst: TStringList;
begin
   lst := TStringList.Create;
   lst.Clear;
   lst.Add('a');
   lst.Add('b');
   lst.Add('c');
   lst.Add('d');

   // Esse path é: /data/data/com.embarcadero.MyApp/files/test.txt
   if not TFile.Exists(System.IOUtils.TPath.Combine(System.IOUtils.tpath.getdocumentspath,'test.txt')) then      
       lst.SaveToFile(System.IOUtils.TPath.Combine(System.IOUtils.tpath.getdocumentspath,'test.txt'));

And I see through Debug that the file is created. When I run the second routine the if not TFile.Exists also detects that the file already exists.

PROBLEMS:

1) When I try to find the file test.txt on Android, I even find this directory "/ data / data /...";

2) I do not know is possible on Android, but I would like to save this file in the same program installation folder. In projects with the Delphi VCL I used the path of the Application.ExeName executable as a reference, which is not supported on Android. Is it possible / indicated to do this on Android?

    
asked by anonymous 21.11.2017 / 20:21

1 answer

0
    procedure TForm1.Button1Click(Sender: TObject);
    var
      TextFile: TStringList;
      FileName: string;
    begin

      try
        TextFile := TStringList.Create;
        try
    {$IFDEF ANDROID}// if the operative system is Android
          FileName := Format('%smyFile.txt', [GetHomePath]);
    {$ENDIF ANDROID}
    {$IFDEF WIN32}
          FileName := Format('%smyFile.txt', [ExtractFilePath(ParamStr(0))]);
    {$ENDIF WIN32}
          if FileExists(FileName) then
          begin
            TextFile.LoadFromFile(FileName); // load the file in TStringList
            ShowMessage(TextFile.Text); // there is the text
          end
          else
          begin
            ShowMessage('File not exists, Create New File');

            TextFile.Text := 'There is a new File (Here the contents)';
            TextFile.SaveToFile(FileName); // create a new file from a TStringList

          end;
        finally
          TextFile.Free;
        end;
      except
        on E: Exception do
          ShowMessage('ClassError: ' + E.ClassName + #13#13 + 'Message: ' +
              E.Message);
      end;
    end;

Credits to Angelim, based on the response from this link

    
21.11.2017 / 20:32