Android Question How to fill B4Xcombobox from JSON data (JSON to ARRAY) ?

Sifu

Active Member
Hello,

I'm trying to get a JSON data to a dropdown B4Xcombobox, but not succeeding.

I also tried to change the maptoarray via a sub found on the forum.
Created the json parser via the online tool.
JSON is simple like: [{"id":"31","albumname":"Album1"},{"id":"32","albumname":"Album2"},{"id":"33","albumname":"Album3"},{"id":"34","albumname":"Album4"}]
B4X:
Sub JobDone (job As HttpJob)
    Select job
        Case readdataALBUMS
            'B4XComboBox1Albums.cmbBox.Clear
            'Dim AlbumsInfo() As String
            ListOfAlbums.Initialize
            If job.Success Then
                Dim res As String
                res = job.GetString
                Log("Response from server albums: " & res)

                Dim parser As JSONParser
                parser.Initialize(res)
                Dim jRoot As List = parser.NextArray
                Log("jRoot: " & jRoot)
                For Each coljRoot As Map In jRoot
                    Dim albumname() As String = coljRoot.Get("albumname")
                    Dim id() As String = coljRoot.Get("id")
                    Log("albumname: " & albumname & " id: " & id)
                    Dim a() As String=mapToArray(albumname)
                    Log("a= " & a(1))
                    B4XComboBox1Albums.cmbBox.Add(a(0))
                Next   
            Else
                Log("ERROR: " & job.ErrorMessage)
            End If
            readdataALBUMS.Release
            
    'other case not needed for this question
    End Select
End Sub

Found below sub here: https://www.b4x.com/android/forum/threads/convert-map-to-array.141176/#content
B4X:
public Sub mapToArray(m As Map) As Object()
    Dim arr(m.Size * 2) As Object  'array size is double of the map because both keys and values are elements
    Dim i As Int=0
    Dim value As Object
    For Each key As Object In m.Keys
        value=m.Get(key)
        LogColor($"key=${key}, value=${value}"$, Colors.blue)
        arr(i)=key
        i = i +1
        arr(i)=value
        i =i +1
    Next
    Return arr
End Sub

Maybe the Sub mapToArray is not needed at all, but I've tried for days, But not succeeding, getting different errors on the way trying to solve.

Or is this easier to do without JSON? Just getting the two values per line and add it to the dropdownmenu?

Thanks for any help.

Best regards
 

Mariano Ismael Castro

Active Member
Licensed User
Hello,

I'm trying to get a JSON data to a dropdown B4Xcombobox, but not succeeding.

I also tried to change the maptoarray via a sub found on the forum.
Created the json parser via the online tool.
JSON is simple like: [{"id":"31","albumname":"Album1"},{"id":"32","albumname":"Album2"},{"id":"33","albumname":"Album3"},{"id":"34","albumname":"Album4"}]
B4X:
Sub JobDone (job As HttpJob)
    Select job
        Case readdataALBUMS
            'B4XComboBox1Albums.cmbBox.Clear
            'Dim AlbumsInfo() As String
            ListOfAlbums.Initialize
            If job.Success Then
                Dim res As String
                res = job.GetString
                Log("Response from server albums: " & res)

                Dim parser As JSONParser
                parser.Initialize(res)
                Dim jRoot As List = parser.NextArray
                Log("jRoot: " & jRoot)
                For Each coljRoot As Map In jRoot
                    Dim albumname() As String = coljRoot.Get("albumname")
                    Dim id() As String = coljRoot.Get("id")
                    Log("albumname: " & albumname & " id: " & id)
                    Dim a() As String=mapToArray(albumname)
                    Log("a= " & a(1))
                    B4XComboBox1Albums.cmbBox.Add(a(0))
                Next  
            Else
                Log("ERROR: " & job.ErrorMessage)
            End If
            readdataALBUMS.Release
           
    'other case not needed for this question
    End Select
End Sub

Found below sub here: https://www.b4x.com/android/forum/threads/convert-map-to-array.141176/#content
B4X:
public Sub mapToArray(m As Map) As Object()
    Dim arr(m.Size * 2) As Object  'array size is double of the map because both keys and values are elements
    Dim i As Int=0
    Dim value As Object
    For Each key As Object In m.Keys
        value=m.Get(key)
        LogColor($"key=${key}, value=${value}"$, Colors.blue)
        arr(i)=key
        i = i +1
        arr(i)=value
        i =i +1
    Next
    Return arr
End Sub

Maybe the Sub mapToArray is not needed at all, but I've tried for days, But not succeeding, getting different errors on the way trying to solve.

Or is this easier to do without JSON? Just getting the two values per line and add it to the dropdownmenu?

Thanks for any help.

Best regards
Hello, here is a possible solution to your problem.

Fill B4XComboBox:
Private Sub FillComboBox
    Dim res As String=$"[{"id":"31","albumname":"Album1"},{"id":"32","albumname":"Album2"},{"id":"33","albumname":"Album3"},{"id":"34","albumname":"Album4"}]"$
    B4XComboBox1Albums.cmbBox.Clear
    Dim items As List
    items.Initialize
    Dim list As List= res.As(JSON).ToList
    For Each colroot As Map In list
        items.Add(colroot.Get("albumname"))
    Next
    B4XComboBox1Albums.SetItems(items)
End Sub
 
Upvote 0

Sifu

Active Member
Hello Mariano,

thanks for your help.
I'm getting an error: java.lang.NullPointerException: null receiver
If I comment out line 3, then I get the error that the combobox class instance is not initialized, which should not be neccessary as I added it via the designer and generated the members for it.

How do I solve that error?

Thank you.
 
Upvote 0

Sifu

Active Member
ok found out via this link https://www.b4x.com/android/forum/t...ew-here-s-how-to-add-programmatically.118037/ that I needed to add a layout with the b4xcombobox on it.
Now the initialization errors are gone. Well that was not clear to me at all. I thought I could put a combobox on any layout I wanted and when loaded its initialized. Seems not. Not clear to me from the guides either.

Anyway, its not filled with data yet.
Hope you have a clue and I will also try some more.


Working! Finally! I have wasted much time with trying. I'm thankful to you @Mariano Ismael Castro !

Best regards.
 
Last edited:
Upvote 0

Mariano Ismael Castro

Active Member
Licensed User
ok descubrí a través de este enlace https://www.b4x.com/android/forum/t...ew-here-s-how-to-add-programmatically.118037/ que yo necesario para agregar un diseño con b4xcombobox en él.
Ahora los errores de inicialización se han ido. Bueno, eso no me quedó nada claro. Pensé que podría poner un cuadro combinado en cualquier diseño que quisiera y cuando se carga se inicializa. Parece que no. Tampoco me queda claro en las guías.

De todos modos, aún no está lleno de datos.
Espero que tengas una pista y también intentaré un poco más.


¡Laboral! ¡Finalmente! He perdido mucho tiempo intentándolo. Te lo agradezco @Mariano Ismael Castro !

Saludos.
Adjunto un ejemplo básico con la función que comparto
 

Attachments

  • ExampleBAXComboBox.zip
    9.6 KB · Views: 116
Upvote 0

Sifu

Active Member
Hello,
I have an additional question. How can I let the headtext be like "Choose album". As now it takes the first albumname of the list which is not direct selectable. it becomes selectable after choosing another first.

Thank you
 
Upvote 0
Top