B4J Question java.lang.NullPointerException - String vs Null vs null

tchart

Well-Known Member
Licensed User
Longtime User
Im using ExecQuerySingleResult to get a value out of a database. Sometime the value is null (to be expected) so I need to check if its null.

However my app is throwing a java.lang.NullPointerException when I try to test the value of the resulting string.

Code is like this;

Dim result As String
result = Main.DB.ExecQuerySingleResult(...)

If I check result.length its fine however if I use result.contains("X") then I get the NullPointerException

If I Log(result) it shows null but even if I test for "null" (ie a sting) or just null (as in null) its still passing the test.

If result .Length > 0 then 'Passes
If result <> "null" then 'Passes
If result <> Null then 'Passes
If result.Contains("appid=") = False Then 'NullPointerException

What is the best/safe way to test for a null value?
 

tchart

Well-Known Member
Licensed User
Longtime User
I found some discussion on this very problem here;


No real solution other then to test for null like this;

B4X:
Sub IsNull(O as Object) as Boolean
       Return (O=Null)
End Sub

From Erels comments it looks like return values from libraries can actually be Null and not an actual string "null".

Ive altered my SQL statement to use IFNULL(field,'') at least then I can be guarenteed its a string.
 
Upvote 0

emexes

Expert
Licensed User
If result .Length > 0 then 'Passes
If result <> "null" then 'Passes
If result <> Null then 'Passes
If result.Contains("appid=") = False Then 'NullPointerException

What is the best/safe way to test for a null value?
What happens with:
B4X:
Dim result As Object = Main.DB.ExecQuerySingleResult(...)
If result Is String Then
    'on the home stretch
Else
    'off in the weeds
End If
 
Upvote 0

tchart

Well-Known Member
Licensed User
Longtime User
Thanks @emexes and @Erel I was hoping for a more universal solution. In this case I need to use ExecQuerySingleResult as I know its only going to be one result. I will just handle the nulls in the query as that is cleaner for me.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
In this case I need to use ExecQuerySingleResult
1. Your solution with the IFNULL SQL statement is excellent and you can indeed keep using ExecQuerySingleResult.
2. There is never a need to use ExecQuerySingleResult. This is just a small helper method that calls ExecQuery internally.
 
Upvote 0

udg

Expert
Licensed User
Longtime User
@tchart : you could use "LIMIT 1" to have a single result from a standard ExecQuery2 query.
 
Upvote 0
Top