Android Question List to Array

Declan

Well-Known Member
Licensed User
Longtime User
I have a String Array that I am creating as follows:
B4X:
    Dim booknames() As String  = Array As String("text_creative_arts.epub",  _
                                                "text_english_reader.epub", _                                     
                                                "text_Life_Orientation.epub",  _                                                                                 
                                                "text_mathematics.epub")

I wish to now create this Array "on-the-fly" by reading the files within the folder.
I can create a List of files, as follows:
B4X:
    Dim ImageList As List
    Dim ImageCount As Int
    ImageList = File.ListFiles("/storage/emulated/0/books/Text/")
    ImageCount = ImageList.Size
 
    Log("File List = " & ImageList)
    Log("File Count = " & ImageCount)
The Log is:
B4X:
File List = (ArrayList) [text_creative_arts.epub, text_english_reader.epub, text_Life_Orientation.epub, text_mathematics.epub]
File Count = 4
How do I create the Array for:
B4X:
Dim booknames() As String  = Array As String()
 

DonManfred

Expert
Licensed User
Longtime User
write a small sub which get the list as parameter and which will create the right array for you with the content of the list and return the newly created array
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
B4X:
Dim booknames(ImageCount) As String
    For i=0 To ImageCount -1
        booknames(i)= ImageList.get(i)
    Next
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
Instead of transforming the List to an Array why not use List for both?
The code in the first post would become:
B4X:
lstBookNames.AddAll(Array As String("text_creative_arts.epub", _
"text_english_reader.epub", _
"text_Life_Orientation.epub", _
"text_mathematics.epub"))
And then access them with lstBookNames.Get(i)
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
ArrayList (https://developer.android.com/reference/java/util/ArrayList.html#toArray()) has a toArray Method that you can access via JavaObject:

B4X:
Dim L As List = File.ListFiles(File.DirRootExternal)
Dim Arr(L.Size) As String = AsJO(L).RunMethod("toArray",Null)
   
For i = 0 To Arr.Length - 1
    Log(Arr(i))
Next

Private Sub AsJO(Jo As JavaObject) As JavaObject
    Return Jo
End Sub

I'm not sure that it will give any noticeable performance gains over doing it yourself in a loop, or using the List directly , but it's there as an option.
 
Upvote 0
Top