Android Question Natural Sort Order in B4X

superkan

Member
Licensed User
List View Sorts to:
Module 0
Module 1
Module 12
Module 15
Module 2
Module 4

But, needed is :
Module 0
Module 1
Module 2
Module 4
Module 12
Module 15

It has been asked before too here https://www.b4x.com/android/forum/threads/ordenar-strings.95662/
but all discussions go towards SQL side of things or altering the item names(padding). I am not using SQL and I need to order a list of files as windows explorer does (see the linked question).
I am new to using Java in B4a so I am asking this. This SO question may be helpful https://stackoverflow.com/questions/23205020/java-sort-strings-like-windows-explorer
 
Last edited:

EnriqueGonzalez

Well-Known Member
Licensed User
Longtime User
you can user List.sortType like this:

B4X:
Sub Process_Globals
    Type ol(nameOfFile As String,value As Int)
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    Dim l As List
    l.Initialize
  
    l.add(Createol("Module 0",0))
    l.add(Createol("Module 1",1))
    l.add(Createol("Module 2",2))
    l.add(Createol("Module 3",3))
    l.add(Createol("Module 12",12))
  
    l.SortType("value",True)
End Sub

Public Sub Createol (nameOfFile As String, value As Int) As ol
    Dim t1 As ol
    t1.Initialize
    t1.nameOfFile = nameOfFile
    t1.value = value
    Return t1
End Sub
 
Upvote 0

superkan

Member
Licensed User
Took some time to test it. It works. Here's how I am using it.

B4X:
Sub GetNumberAtTheNameOfFile(xfilename As String,errorCaseValue As Int) As Int
    Dim m As Matcher = Regex.Matcher("(\d+)$", xfilename) 'handles 34ForceTechnique56OfFighting12 too
    If m.Find Then                                                                     '(\d+) only, if extension present too
        Dim number As Int = m.Group(1) 'm.Group(m.GroupCount) if extension present too
        'Log(number)
        Return number
    Else
        Return errorCaseValue
    End If
End Sub

'Populate the list in a loop with
l.add(Createol(yName,GetNumberAtTheNameOfFile(yName,0)))

'sort
l.SortType("value",True)

'extract back from the list - names
  Dim resOL As ol
  'in a loop :
  resOL = l.get(i)
  ListView1.AddSingleLine(resOL.nameOfFile)
 
Last edited:
Upvote 0
Top