Android Question What is it with null not being zero

Robert Valentino

Well-Known Member
Licensed User
Longtime User
Hello:

If I have a string set to "" (Null) or Empty why does the application crash if I try and assign it to an int

B4X:
Dim TestString as String
Dim TestCount as Int

TestString = ""  ' Set as Empty String

TestCount = TestString   '  This instruction will fail because the string is Null and I get invalid double

Why isn't a null string or a string with just spaces handled as a Zero?

Before the gang wagon jumps on, let me explain my reasoning.

MOST of the time I do not want a Zero to be displayed. So I have to set the input field as "" so nothing shows.

Now every time I need to do something with the value I need to check to see if the length is zero

I am not a basic programmer, but I would have thought basic would treat a null string or a string containing only spaces as a Zero.

To me this seems only logical, but I am sure someone has a reason for this?

Is there a way to not show a Zero in an input field but have a zero there or have a null or space there and not have the program crash on assigning it to an INT variable. As I am typing this I guess I just answered my own question. I guess I need to write a _atol function and always us that for assignment's instead of INT = <Field>.text

Just wondering why Basic4Android doesn't do this for me when casing from text to numeric

Thanks

BobVal
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Note that empty string is not Null.

You can easily create such a sub:
B4X:
Sub S2I (S As String) As Int
 If S = "" Then Return 0
 Return S
End Sub

You can also test whether the string is a valid number with IsNumber.
Just wondering why Basic4Android doesn't do this for me when casing from text to numeric
Basic4ppc did convert empty strings to zeros. The performance overhead and the complexity of this check is much higher than you might expect as it needs to be done everywhere.

An empty string is not a number. In the 0.1% cases where you do need to convert it then you can use a simple sub as the one above.
 
Upvote 0
Top