B4J Question [SOLVED] Why would a button send the information for a previously clicked button?

Zeppah

Member
I have five buttons that use an event. The event is to change the colors of the buttons and to set the user's choice. One of the buttons is sending the information as if it is the last button that was selected. I am plum out of ideas.
B4X:
'I have five buttons that use this event, four work and one button only sends
'The information for the last button pressed
'Button All is not changing the Sender, it is sending the code for the last button pressed
'
Sub PracticeMode_Click
    Log(Sender)
    CSSUtils.SetBackgroundColor(OldButton, fx.Colors.White)
    CSSUtils.SetBackgroundColor(Sender, fx.Colors.LightGray)
    OldButton = Sender
    PracticeNumber = OldButton.Tag
End Sub
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
It is a bit difficult to explain this one. Button is a "wrapper" object. The problem happens because you mix the assignments of OldButton with both the exact type and the non-exact type:
B4X:
OldButton = btnAll
'and later:
OldButton = Sender

It will work properly if you change it to:
B4X:
Sub PracticeMode_Click
    Dim btn As Button = Sender
    CSSUtils.SetBackgroundColor(OldButton, fx.Colors.White)
    CSSUtils.SetBackgroundColor(btn, fx.Colors.LightGray)
    OldButton = btn
    PracticeNumber = OldButton.Tag
End Sub
Or Dim OldButton before you assign it:
B4X:
Dim OldButton As Button = Sender
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
The problem starts here:
B4X:
OldButton = btnAll
As both objects are of the same type, a new wrapper is not created. This means that both variables now point to the same wrapper.

Later the wrapper inner object is set:
B4X:
OldButton = Sender
Now btnAll actually points to the wrong button.

I might change the behavior of wrapper to wrapper assignments at some point to avoid this issue. Need to carefully check that there aren't other side effects for such change.
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
I might change the behavior of wrapper to wrapper assignments at some point to avoid this issue. Need to carefully check that there aren't other side effects for such change.
I've been thinking about this - that's dangerous I know. :D
As both objects are of the same type, a new wrapper is not created
This is what I peronally would expect. An assignment of same type objects looks like a reference assignment so they are both the same object.

If the objects are of different types then a new wrapper could be created. This means cross-type assignments effectively become copy operations which seems reasonable as being different types I wouldn't expect them to necessarily point to the same object.
 
Upvote 0

Zeppah

Member
Thank you very much Erel! I am fairly new to programming so I don't understand wrappers (yet) but I will definitely research them now. :)
Your fix worked properly just as you said it would.
 
Upvote 0
Top