Android Question A simple calculator closes down

Hello,

In attached project, it's a simple calculator, I got it to work, however, when pressing any sign (like + or -) for more than once, the app closes

I believe the problem could be in (docalc) sub, the following:
B4X:
Sub docalc (math As String,newmath As String)
    If math = "plus" Then
        total = nr1 + nr2
    Else If math = "minus" Then
        total = nr1 - nr2
    Else If math = "mul" Then
        total = nr1 * nr2
    Else If math = "div" Then
        total = nr1 / nr2
    Else If math = "percent" Then
        total = nr1 / 100
    Else
        Return
    End If
    If newmath <> "" Then
        mathstr = newmath
        nr2 = ""
    Else
        mathstr = ""
        nr2 = ""
    End If
    nr1 = total
    totallb1.Text = NumberFormat(total, 0, 30) & space
End Sub

Thank you for helping with it
 

Attachments

  • calculator debug.zip
    10.7 KB · Views: 7

Brian Dean

Well-Known Member
Licensed User
Longtime User
I added this line to your code in Sub docalc :

B4X:
Sub docalc (math As String,newmath As String)
    Log("nr1 = " & nr1 & " ; nr2 = " & nr2)   ' <===

If you tap any sign key twice then you will see that Sub docalc is called, but nr2 is empty (blank). That is what causes the crash. You will need to detect the situation where an operator key is pressed twice in succession and prevent Sub docalc being called, or you could check in "docalc" that neither of the arguments are empty.

Have you tried running in "Debug" mode? That helps you locate problems like this more quickly. Also your screen layout needs to be more adaptable; on my phone (Pixel 4a) the operator keypads are only just visible at the edge of the screen in portrait mode.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…