Android Question Loading variables with values using a do loop

Kevin Hartin

Active Member
Licensed User
In PHP I often read a bunch of key pairs from a SQL table and load up variables using somethng like;
PHP WHILE:
while ($rw = mysqli_fetch_array($rs, MYSQLI_ASSOC)) {
    foreach($rw as $key=>$val){
        ${$key} = $val;
    }
}
This is particularly useful for filling in Report Templates.

Is there any way to dynamically create and assign a value to something like a sequentially numbered bunch of buttons. I have a handheld POS system with 14 buttons to a page and they are dynamically loaded from a sqlite DB when a page loads or changes. Right now I have effectively got the same code repeated 14 times, which is cumbersome.
B4X:
    If lstID.Get(0) > 0 Then
        btnPOS0.Tag = lstID.Get(0)
        btnPOS0.Text = lstItem.Get(0)&CRLF&"$"&NumberFormat2(lstPrice.Get(0),1,2,2,False)
    Else
        btnPOS0.Visible = False
    End If
    If lstID.Get(1) > 0 Then
        btnPOS1.Tag = lstID.Get(1)
        btnPOS1.Text = lstItem.Get(1)&CRLF&"$"&NumberFormat2(lstPrice.Get(1),1,2,2,False)
    Else
        btnPOS1.Visible = False
    End If
...
    If lstID.Get(13) > 0 Then
        btnPOS13.Tag = lstID.Get(13)
        btnPOS13.Text = lstItem.Get(13)&CRLF&"$"&NumberFormat2(lstPrice.Get(13),1,2,2,False)
    Else
        btnPOS13.Visible = False
    End If
Obviously I could easily loop through the List lstID, but how can I set 14 buttons text attributes such as btnPOS0, btnPOS1...btnPOS13 using a loop and my Lists?

Thanks,
Kev
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You should never repeat code.
There are many ways to organize the various objects.

Example:
B4X:
Dim buttons As List = Array(btnPOS0, btnPOS1, ...)

For i = 0 To buttons.Size - 1
 Dim btn As B4XView = buttons.Get(i)
 btn.Tag = lstID.Get(i)
 btn.Text = lstItem.Get(i)&CRLF&"$"&NumberFormat2(lstPrice.Get(i),1,2,2,False)
Next
 
Upvote 0
Top