Android Question Strange Activity_KeyPress & if statement

incendio

Well-Known Member
Licensed User
Hi guys,

I have 2 codes,
Code A
B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean
   If KeyCode = KeyCodes.KEYCODE_BACK then
      If Info.IsShow then
         Info.Close
         Return True
      End If
   End If
   Return False
End Sub

Code B
B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean 'return true if you want to consume the event
    If KeyCode = KeyCodes.KEYCODE_BACK And Info.IsShow Then
        Info.Close
        Return True
    End If
    Return False
End Sub

Info is a class that was never initialize before Sub Activity_KeyPress called. Those codes should return the same result, right?
But, they were not.

Code A, raised an error, null pointer operation. But, code B, runs without errors.

Am I missing something here?
 

agraham

Expert
Licensed User
The return value is definitely needed.

You haven't really given enough precise information but it is probably because Java, and hence B4X, short circuits conditional expression evaluation so in Code B, unless the key code is KEYCODE_BACK then Info.IsShow is not evaluated (because the expression can never be True) and hence does not raise the error.
 
Upvote 0

incendio

Well-Known Member
Licensed User
The return value is definitely needed.

You haven't really given enough precise information but it is probably because Java, and hence B4X, short circuits conditional expression evaluation so in Code B, unless the key code is KEYCODE_BACK then Info.IsShow is not evaluated (because the expression can never be True) and hence does not raise the error.
I am sorry if I don't understand your replied correctly, English is not my native language.

Are you saying that in Code B, even back key was pressed, info.IsShow wasn't evaluated because some bug in Java?
 
Upvote 0

agraham

Expert
Licensed User
Are you saying that in Code B, even back key was pressed, info.IsShow wasn't evaluated because some bug in Java?
No. Only if the back key is pressed is Info.IsShow evaluated. It is not a bug, it is a deliberate design choice for Java. C# also has short circuit logical expression evaluation as do many other computer languages. I don't know if this is the source of the difference you see as you have not supplied enough information about the circumstances when you see the error.
 
Upvote 0

Sagenut

Well-Known Member
Licensed User
Is it possible something like this?
B4X:
Sub Activity_KeyPress (KeyCode As Int) As Boolean
   If KeyCode = KeyCodes.KEYCODE_BACK then
      If Info.IsInitialized and Info.IsShow then
         Info.Close
         Return True
      Else
         Return False
      End If
   End If
End Sub
 
Upvote 0
Top