Android Tutorial Android FTP tutorial

Status
Not open for further replies.
Old and irrelevant tutorial. Follow this one instead: [B4X] Net library (FTP, SMTP, POP) with Wait For

This tutorial covers the FTP object which is part of the Net library.
The Net library is based on Apache Commons Net.

Android OS doesn't allow us, the developers, to block the main thread for more than 5 seconds. When the main thread is busy for too long and is not able to handle the user events the "Application not responding" dialog appears.
Therefore slow operations like network operations should be done in the background.
The FTP library is built in such a way. All of the methods return immediately. When a task completes an event is raised. In fact you can submit several tasks one after another. The FTP protocol supports a single task at a time so the tasks will be processed serially.

Using the FTP library is pretty simple.
The first step is to initialize the FTP object. If this is an Activity module then you should do it in Activity_Create when FirstTime is true.
For Service modules it should be initialized in Service_Create.
B4X:
Sub Process_Globals
    Dim FTP As FTP
End Sub
Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        FTP.Initialize("FTP", "ftp.example.com", 21, "user", "password")
    End If
FTP.Initialize doesn't connect to the server. Connection will be established implicitly together with the next task.

Download

Downloading a file is done by calling DownloadFile with the remote file path and the local file path.
If you want to show the download progress then you should handle DownloadProgress event.
When download completes the DownloadCompleted event is raised. The ServerPath is passed as the first parameter to all events. You can use it to distinguish between different tasks. Make sure to check the Success parameter. If Success is False then you can find the exception message by calling LastException.

B4X:
    FTP.DownloadFile("/somefolder/files/1.zip", False, File.DirRootExternal, "1.zip")
   
Sub FTP_DownloadProgress (ServerPath As String, TotalDownloaded As Long, Total As Long)
    Dim s As String
    s = "Downloaded " & Round(TotalDownloaded / 1000) & "KB"
    If Total > 0 Then s = s & " out of " & Round(Total / 1000) & "KB"
    Log(s)
End Sub

Sub FTP_DownloadCompleted (ServerPath As String, Success As Boolean)
    Log(ServerPath & ", Success=" & Success)
    If Success = False Then Log(LastException.Message)
End Sub
Upload

Uploading is similar to downloading.
B4X:
    FTP.UploadFile(File.DirRootExternal, "1.txt", True, "/somefolder/files/1.txt")

Sub FTP_UploadProgress (ServerPath As String, TotalUploaded As Long, Total As Long)
    Dim s As String
    s = "Uploaded " & Round(TotalUploaded / 1000) & "KB"
    If Total > 0 Then s = s & " out of " & Round(Total / 1000) & "KB"
    Log(s)
End Sub

Sub FTP_UploadCompleted (ServerPath As String, Success As Boolean)
    Log(ServerPath & ", Success=" & Success)
    If Success = False Then Log(LastException.Message)
End Sub
List files and folders

FTP.List sends a request for the list of files and folders in a specific path.
The ListCompleted event is raised when the data is available.
You can use code similar to the following code to get more information on the entries:
B4X:
FTP.List("/")
...
Sub FTP_ListCompleted (ServerPath As String, Success As Boolean, Folders() As FTPEntry, Files() As FTPEntry)
    Log(ServerPath)
    If Success = False Then
        Log(LastException)
    Else
        For i = 0 To Folders.Length - 1
            Log(Folders(i).Name)
        Next
        For i = 0 To Files.Length - 1
            Log(Files(i).Name & ", " & Files(i).Size & ", " & DateTime.Date(Files(i).Timestamp))
        Next
    End If
End Sub
Delete
Delete is done by calling FTP.Delete with the full path. Again an event will be raised when the task completes (DeleteCompleted).

Closing the connection
You can close the connection by calling FTP.Close. Close will wait for the other tasks to complete and then will close the connection. This happens in the background.
FTP.CloseNow will immediately close the connection, failing the remaining tasks.

Some notes:
- At any given time there should be less than 15 waiting tasks. Otherwise you will get a RejectedExecutionException (this happens when the internal threads pool is exhausted).
- The order of the completed tasks may be different than the order of submission.
- The AsciiFile parameters sets the file transfer mode. If AsciiFile is true then every occurrence of an end of line character will be translated based on the server native end of line character. If your FTP server is Unix or Linux then the end of line character is the same as Android.
In most cases you can set AsciiFile to false.

The library is available for download here: http://www.b4x.com/forum/additional...92-new-net-library-android-ftp-smtp-pop3.html
 
Last edited:

sultan87

Active Member
Licensed User
Longtime User
You can use a List command to test the connection. If Success is True then the connection is good.
Hello,
thank you
I did the test with the following code

Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
' Activity.LoadLayout("Main")
FTP.Initialize("FTP", "ftpperso.free.fr", 21, "xxx", "yyyy")
End If

FTP.List("/")

End Sub

1 the correct login, no message
2 incorrect login error message
3 wifi does not work, error message
so ok

I added a download of a file

Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
' Activity.LoadLayout("Main")
FTP.Initialize("FTP", "ftpperso.free.fr", 21, "xxx", "yyyyy")
End If

FTP.List("/")

FTP.DownloadFile("/Bridge/BD/bridge_donnes.db", False, File.DirDefaultExternal, "bridge_donnes_2.db")

End Sub

if there is an error detected by FTP.List, I do not want the FTP.Download runs, how?

Best Regards
 

sultan87

Active Member
Licensed User
Longtime User
Please use [ code ] [ /code ] tags (without spaces) when posting code.

You should handle the ListCompleted event.

Hello,
I handled the event ListCompleted.

[ code ]

Sub FTP_ListCompleted (ServerPath As String, Success As Boolean, Folders() As FTPEntry, Files() As FTPEntry)
Log(ServerPath)

If Success = False Then
Log("FTP List " & LastException)
Else
For i = 0 To Folders.Length - 1
Log(Folders(i).Name)
Next
For i = 0 To Files.Length - 1
Log(Files(i).Name & ", " & Files(i).Size & ", " & DateTime.Date(Files(i).Timestamp))
Next
End If
End Sub

[ /code ]

Best Regards
 

sultan87

Active Member
Licensed User
Longtime User
You should call FTP.Download from inside FTP_ListCompleted (if Success is true).

Hello,
Thank you for your help
it works correctly
I am developing a personal application that can be used from my tablet or my smartphone.
This application uses an SQLite database that I put on a server.
this is why I use FTP to retrieve the BD
How to synchronize the bd on the smartphone, the tablet and the server?
best regards
 

bluedude

Well-Known Member
Licensed User
Longtime User
How do I know which file has been uploaded completely in the upload event? I cannot find a file ID or something like that.
 

DonManfred

Expert
Licensed User
Longtime User
How do I know which file has been uploaded completely in the upload event? I cannot find a file ID or something like that.

B4X:
Sub FTP_UploadCompleted (ServerPath As String, Success As Boolean)
  if Success then
    log("The file "&ServerPath&" is successfully uploaded")
  end if
END SUB
 

DonManfred

Expert
Licensed User
Longtime User
On what exactly you have a problem with? Have you tried the lib? Do you get any error?
See ftp-tutorial. If you want to use resume then you have to use the object ftpresume instead of ftp (and using the netextras lib instead of net). But anything else should be the same like in the ftp-tutorial
 

leitor79

Active Member
Licensed User
Longtime User
Hi!

My FTP_UploadCompleted event is never fired event if the upload is successful.

I have the FTP object on a code module... could that be the reason? Must the FTP object be on a service module?

Thank you!


PS:

The unfiltered logs shows nothing.
 
Last edited:
Status
Not open for further replies.
Top