Android Code Snippet get all image folders (path)

This code runs on my phone in release with 156ms. And i have over 1k folders and over 10k images.

usage:
    Dim tmp_lst As List : tmp_lst.Initialize   
    GetAllFolders(tmp_lst,File.DirRootExternal,File.DirRootExternal)
    
    For Each image_path As String In tmp_lst
        Log(image_path)
    Next

B4X:
'https://www.b4x.com/android/forum/threads/recursive-directorystructures-and-what-to-do-with-this-filelist.40560/#content
Public Sub GetAllFolders(tmp_lst As List,folder As String,root_path As String)
    Dim lst As List = File.ListFiles(folder)
    For i = 0 To lst.Size - 1
        If File.IsDirectory(folder,lst.Get(i)) Then
            Dim v As String = folder&"/"&lst.Get(i)
            If FolderHasImages(v) = True Then
                tmp_lst.Add(v.SubString(root_path.Length+1))
                GetAllFolders(tmp_lst,v,root_path)
            End If
        End If
    Next
End Sub

Private Sub FolderHasImages(folder As String) As Boolean
    For Each tmp_file As String In File.ListFiles(folder)
        If tmp_file.EndsWith(".jpg") Or tmp_file.EndsWith(".jpeg") Or tmp_file.EndsWith(".png") Or tmp_file.EndsWith(".gif") Or tmp_file.EndsWith(".bmp") = True Then Return True
    Next
    Return False
End Sub
 

GeoT

Active Member
Licensed User
Hello.

Your code only lists the root folders that contain images. If that first parent folder does not contain images, although its children do, it does not list her or her child folders.
I have modified your code so that it does.

B4X:
Public Sub GetAllFolders(tmp_lst As List,folder As String,root_path As String)

    Dim lst As List = File.ListFiles(folder)
    Dim forbidden As Boolean

    For i = 0 To lst.Size - 1
        If File.IsDirectory(folder,lst.Get(i)) Then
            Dim v As String = folder&"/"&lst.Get(i)
        
            If FolderHasImages(v) = True Then

                Dim path As String = v.SubString(root_path.Length+1)
                If path.StartsWith("Android/data/") Or path.IndexOf(".") > -1 Then
                    forbidden = True
                Else
                    forbidden = False
                End If
            
                If forbidden = False Then tmp_lst.Add(path)

            End If
            GetAllFolders(tmp_lst,v,root_path)
        End If
    Next
End Sub

And I have excluded the Android folder and those that start with a period like this, because the contains method of the strings was not working for me.

It has been slow to do it 1.356 sec and obviously I had to add the RuntimePermissions code.


Regards
 
Last edited:
Top