Android Question Code in event doesn't seem to run when Wait For is used

Andrew Gray

Member
Licensed User
Longtime User
I have code like the following. The Wait For part works fine, and does indeed resume when the button is clicked. But the code in Button_Click never runs (ClickedButton, which a global variable, thus remains empty).

B4X:
Sub MainModule
    
    Do While True
        Wait For Button_Click
        Log("You clicked " & ClickedButton)
    Loop
    
End Sub

Sub Button_Click

    Dim btn As Button = Sender
    ClickedButton = btn.Text

End Sub

Does Wait For somehow consume the button click event? And how can I fix this?

(This is to help a high school student with a coding exercise so I don't need a best practice solution, I just want a solution that is simple and works!)
 
Does Wait For somehow consume the button click event?
Yes. It handles the event.

And how can I fix this?
In most cases you don't need the event sub at all, however if it is important for you then call it yourself:
Code:
Sub MainModule
   
    Do While True
        Wait For Button_Click
        Log("You clicked " & ClickedButton)
        Button_Click '<----------------------------
    Loop
   
End Sub

Sub Button_Click

    Dim btn As B4XView = Sender
    ClickedButton = btn.Text

End Sub
 
Upvote 0
The issue lies in the fact that the Wait For statement is consuming the button click event before it can be handled by the Button_Click subroutine. This is why the code in Button_Click is not executed, and the ClickedButton variable remains empty.

To resolve this issue, you can modify the code by introducing a flag variable to track whether a button click has occurred. look here

Sub MainModule

Dim ButtonClicked As Boolean = False ' Flag variable to track button clicks

Do While True
If ButtonClicked Then
Log("You clicked " & ClickedButton)
ButtonClicked = False ' Reset the flag
End If
Wait For Button_Click
' Button_Click event will set the flag and assign the clicked button text
Loop

End Sub

Sub Button_Click

Dim btn As Button = Sender
ClickedButton = btn.Text
ButtonClicked = True ' Set the flag to indicate a button click

End Sub

By introducing the ButtonClicked flag, you can check if a button click has occurred inside the loop. If a button click has been registered, you can log the clicked button's text and reset the flag. This ensures that the code in Button_Click is executed and the ClickedButton variable is updated accordingly.

Thanks. However, if Wait For consumes the event, the flag setting code would still not run.

In the end I managed to get the program working by using Sleep rather than Wait For...

B4X:
Sub Button_Click
    Dim btn As Button = Sender
    ClickedWord = btn.Text
End Sub

Sub MainModule
    
    Do While True
        Do While ClickedWord = ""
            Sleep(100)
        Loop
        Log("You clicked " & ClickedWord)
        ClickedWord = ""
    Loop
    
End Sub
 
Upvote 0
Back
Top