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?
Upfront disclaimer: I've been working on my latest project pretty hard for the past few weeks, so I'm getting very tired... I have a sub that takes a String argument & returns a bitmap. I perform a test on the string to see if it's Null & if it isn't loads the file in the string, else it loads...
www.b4x.com
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.
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?
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.
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.