B4J Question Resumable subs with recursive File.ListFiles to update UI

walt61

Active Member
Licensed User
Longtime User
Hi all,

I'm trying to get my head around this but have tried a number of things with Sleep and Wait For, all of which failed. I think it's the recursion that gets in my way but perhaps am missing something else.

I want to get a folder's (and its subfolders') contents and display the folder currently being searched in a label. Without resumable subs, the UI of course isn't updating so the label's text doesn't change.

Any hints would be greatly appreciated!

B4X:
Sub SomeSub

    GetTheFolderContents("C:\somefolder")

End Sub

Sub GetTheFolderContents(fldr As String)

    LabelFolder.Text = fldr ' Show this folder

    For Each x In File.ListFiles(fldr)
        If File.IsDirectory(fldr, x) Then
            GetTheFolderContents(File.Combine(fldr, x)) ' Found a subfolder; process it
            LabelFolder.Text = fldr ' Show this folder again after returning from a subfolder
        Else
            fList.Add(File.Combine(fldr, x)) ' Found a file; add it to list 'fList'
        End If
    Next

End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
The recursion does make it more complicate. Remember that Sleep causes the code flow to return so the parent sub will immediately continue.

The simplest solution in this case is to use a non-recursive solution:
B4X:
Sub GetTheFolderContents (fldr As String)
   Dim folders As List
   folders.Initialize
   folders.Add(fldr)
   Do While folders.Size > 0
     fldr = folders.Get(0)
     folders.RemoveAt(0)
     labelFolder.Text = fldr ' Show this folder
     MainForm.Title = $"Total files:${flist.Size}"$
     Sleep(0)
     Dim entries As List = File.ListFiles(fldr)
     If entries.IsInitialized Then
       For Each x As String In entries
         If File.IsDirectory(fldr, x) Then
           folders.Add(File.Combine(fldr, x)) ' Found a subfolder
         Else
           flist.Add(File.Combine(fldr, x)) ' Found a file; add it to list 'fList'
         End If
       Next
     End If
   Loop
End Sub
 
Upvote 0
Top