Android Question testing for null vs using isInitialized?

Dave O

Well-Known Member
Licensed User
Longtime User
I'm not clear on the difference between testing an object for NULL vs. using isInitialized.

I ran into this because I passed a Null value into a sub, but it crashed on an "object not initialized" error. Here's the code:

B4X:
tip1.addTipForArea(tempRect, Null, "foobar", "barfoo")

Public Sub addTipForArea(rectArg As Rect, svArg As ScrollView, titleArg As String, descArg As String)
   ...some code here
   If svArg <> Null Then
       rectArg.top = rectArg.Top + svArg.Top
       rectArg.Bottom = rectArg.Bottom + svArg.top
   End If
   ...more code here
End Sub


It works fine if I replace the IF with this:
B4X:
If (svArg.IsInitialized) And (svArg <> Null) Then

Why doesn't the first version work? Because a Null passed as an argument isn't actually initialized?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
If (svArg.IsInitialized) And (svArg <> Null) Then
This line is wrong. The second clause will never be reached.

The safest check is:
B4X:
If svArg <> Null AND svArg.IsInitialized Then
 ...

Practically in this case it will never be null because ScrollView is implemented as a "wrapper" object. When you pass Null to a wrapper type it is automatically converted to an uninitialized object.
 
Upvote 0
Top