Android Question Listview Sort accordig to Second lines

tufanv

Expert
Licensed User
Longtime User
Hello,

I am using the listview with twolinesandbitmap. I have tl.first and tl.second values for creating the list with 2 lines. I want to sort the listview according to second line ( second lines are dates i want to sort the list with the newest date first )

Is there any example or code you can share ?

TY
 

Linostar

Member
Licensed User
Longtime User
First, make sure you use AddTwoLinesAndBitmap2 in the listview. It allows you to add a ReturnValue, which will be the same as as the second line in your case. We will get this ReturnValue when we call tl.getItem, and then we will be able to sort based on the second line of each item.

Furthermore, since a listview won't allow you to access item bitmaps after you initally add them, you need to store them beforehand (along with the two lines) in seperate lists.

B4X:
Dim firstLabels As List
Dim secondLabels As List
Dim Icons As List
firstLabels.Initialize
secondLabels.Initialize
Icons.Initilaize

'...

tl.AddTwoLinesAndBitmap2(firstLine, secondLine, LoadBitmap(File.DirAssets, ImageName), secondLine)
firstLabels.Add(firstLine)
secondLabels.Add(secondLine)
Icons.Add(ImageName)

Now to the Sorting sub:

B4X:
Sub BubbleSort(LV As ListView)
    Dim swapped As Boolean
    Dim IndexArr(LV.size) As Int
    Dim i As Int, temp As Int
    swapped = True
    For i = 0 To LV.size -1
          IndexArr(i) = i
    Next
    Do While swapped
          swapped = False
          For i = 1 To LV.size - 1
                If LV.GetItem(i - 1) > LV.GetItem(i) Then
                        temp = IndexArr(i - 1)
                        IndexArr(i-1) = IndexArr(i)
                        IndexArr(i) = temp
                        swapped = True
                End If
          Next
    Loop
    
     'Add the sorted values to the original ListView
     LV.Clear
     For i = 0 To LV.size -1
           LV.AddTwoLinesWithBitmap2(firstLabels(IndexArr(i)), secondLabels(IndexArr(i)), _
                LoadBitmap(File.DirAsstes, Icons(IndexArr(i))), secondLabels(IndexArr(i)))
     Next
End Sub

Finally, you only need to call the BubbleSort sub:

B4X:
BubbleSort(tl)


I didn't test the code, so I can't guarantee its correctedness.
 
Upvote 0

tufanv

Expert
Licensed User
Longtime User
I solved the problem with sorting the database first and than adding to listview. Ty very much for your help Linostar !
 
  • Like
Reactions: eps
Upvote 0
Top