Android Question B4XFloatTextField Check if empty

Declan

Well-Known Member
Licensed User
Longtime User
How can I check if both of the two B4XFloatTextField have text?
When the user clicks "OK", I must check that data has been entered each of the B4XFloatTextField.
If either is empty, I display a ToastMessage.
I must then set focus on the B4XFloatTextField that is empty.

My code (that does not work)

B4X:
Sub CheckForUser
    DB.Initialize(DBFileDir, DBFileName, True)
    Dim Cursor As Cursor
    Cursor = DB.ExecQuery("SELECT * FROM reg")
   
    If (Cursor.RowCount < 1) Then
        Log("No USER")
       
        dialog.Initialize(Activity)
        dialog.Title = "Login"
       
        Dim p As B4XView = xui.CreatePanel("")
        p.SetLayoutAnimated(0, 0, 0, 300dip, 150dip)
        p.LoadLayout("CustomDialog")
        dialog.PutAtTop = True 'put the dialog at the top of the screen
        Wait For (dialog.ShowCustom(p, "OK", "", "CANCEL")) Complete (Result As Int)
        If Result = xui.DialogResponse_Positive Then
            If (txtUsername.Text = "") Then
                ToastMessageShow("You MUST enter your Username", False)
            End If
           
            If (txtPassword.Text = "") Then
                ToastMessageShow("You MUST enter your Password", False)
            End If
           
            If (txtUsername.Text <> "" And txtPassword.Text <> "") Then
                dialog.Show("Welcome", "OK", "", "")
                currentUser = txtUsername.Text
                currentPwd = txtPassword.text

                getUser(currentUser)
            End If
        End If
       
        If Result = xui.DialogResponse_Cancel Then
            ToastMessageShow("You MUST Login to Continue", True)
            Sleep(3000)
            ExitApplication
        End If
       
    End If
   
    If (Cursor.RowCount > 0) Then
        Log("GOT USER")
        ' Get fleet from SQLite table "reg"
'        getFleet
    End If
End Sub
 

Mahares

Expert
Licensed User
Longtime User
Something like this: Make sure you initialize the database only if firsttime in activity_Create:
B4X:
If FirstTime Then
        DB.Initialize(DBFileDir, DBFileName, True)
    End If
B4X:
Sub Button1_Click
    Dim cursor As ResultSet  = DB.ExecQuery("SELECT * FROM reg")
    If cursor.RowCount >0 Then
        Dialog.Initialize(Activity)
        Dialog.Title = "User/Password login"
      
        Dim currentUser As String
        Dim currentPwd  As String
      
        Dim p As B4XView = xui.CreatePanel("")
        p.SetLayoutAnimated(0, 0, 0, 300dip, 400dip)
        p.LoadLayout("CustomDialog")   'has both B4XFloatTextField
        Dialog.PutAtTop = True
        Dim rs As ResumableSub = Dialog.ShowCustom(p, "OK", "", "CANCEL")
        txtUsername.RequestFocusAndShowKeyboard
      
        IsDialogValid(txtUsername.Text, txtPassword.text)
        Wait For (rs) Complete (Result As Int)  
        If Result = xui.DialogResponse_Positive Then
            currentUser = txtUsername.Text
            currentPwd = txtPassword.text          
            Dialog.Show($"Hello ${currentUser} ${currentPwd}"$, "OK", "", "")
        End If
    Else
        Log("Use is not in the database")
    End If
cursor.close
End Sub

Private Sub IsDialogValid (user As String, pwd As String)
    Dim ok As B4XView = Dialog.GetButton(xui.DialogResponse_Positive)
    If user.Length > 0 And pwd.Length > 0 Then
        ok.Enabled = True
    Else
        ToastMessageShow("You MUST enter your Username/password", True)
        ok.Enabled = False
    End If
End Sub

Sub txtUsername_TextChanged (Old As String, New As String)
    If Dialog.Visible = False Then Return
    IsDialogValid(New, txtPassword.Text)
End Sub

Sub txtPassword_TextChanged (Old As String, New As String)
    If Dialog.Visible = False Then Return
    IsDialogValid(txtUsername.Text, New)
End Sub
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Use B4XPages.
Add Return when a value is empty.

B4X:
Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private DB As SQL
    Private DBFileDir As String = xui.DefaultFolder
    Private DBFileName As String = "Data.db"
    Private txtPassword As B4XFloatTextField
    Private txtUsername As B4XFloatTextField
End Sub

Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
   
    If File.Exists(DBFileDir, DBFileName) Then
        DB.Initialize(DBFileDir, DBFileName, False)
    Else
        DB.Initialize(DBFileDir, DBFileName, True)
        DB.ExecNonQuery($"CREATE TABLE reg
        (username TEXT,
        password  TEXT,
        firstname TEXT,
        lastname TEXT,
        age INTEGER
        )"$)
        DB.ExecNonQuery($"INSERT INTO reg (username, password, firstname, lastname, age)
        VALUES ('a', 'a', 'John', 'Doe', 21)"$)
        ToastMessageShow("Database created", False)
    End If
End Sub

Private Sub BtnLogin_Click
    CheckForUser
End Sub

Sub CheckForUser
    Try
        'Dim Cursor As ResultSet = DB.ExecQuery("SELECT * FROM reg")
        'If (Cursor.RowCount < 1) Then
        'Log("No USER")
        Dim dialog As B4XDialog
        dialog.Initialize(Root)
        dialog.Title = "Login"
        dialog.PutAtTop = True 'put the dialog at the top of the screen
   
        Dim p As B4XView = xui.CreatePanel("")
        p.SetLayoutAnimated(0, 0, 0, 400dip, 300dip)
        p.LoadLayout("CustomDialog")
        Wait For (dialog.ShowCustom(p, "OK", "", "CANCEL")) Complete (Result As Int)
        If Result = xui.DialogResponse_Positive Then
            If txtUsername.Text = "" Then ' <-- brackets are not required
                ToastMessageShow("You MUST enter your Username", False)
                Return ' <-- To EXIT from further code execution
            End If
         
            If txtPassword.Text = "" Then ' <-- brackets are not required
                ToastMessageShow("You MUST enter your Password", False)
                Return ' <-- To EXIT from further code execution
            End If
       
            'If (txtUsername.Text <> "" And txtPassword.Text <> "") Then
            '    dialog.Show("Welcome", "OK", "", "")
            '    currentUser = txtUsername.Text
            '    currentPwd = txtPassword.text
            '
            '    getUser(currentUser)
            'End If
           
            Dim GotUser As Boolean
            Dim Query As String = "SELECT * FROM reg WHERE username = ? AND password = ?"
            Dim Cursor As ResultSet = DB.ExecQuery2(Query, Array As String(txtUsername.Text, txtPassword.Text))
            Do While Cursor.NextRow
                Log("USER LOGIN SUCCESSFUL")
                GotUser = True
                Log(Cursor.GetString("firstname") & " " & Cursor.GetString("lastname"))
                Log(Cursor.GetInt("age"))
                xui.MsgboxAsync("Login Successful", "LOGIN")
            Loop
            Cursor.Close
       
            If Not(GotUser) Then
                Log("USER NOT FOUND OR PASSWORD NOT MATCH")
                xui.MsgboxAsync("Login Failed", "LOGIN")
            End If
        Else
            ToastMessageShow("You MUST Login to Continue", True)
        End If
     
        'If Result = xui.DialogResponse_Cancel Then
        '    ToastMessageShow("You MUST Login to Continue", True)
        '    Sleep(3000)
        '    ExitApplication
        'End If
 
        'If (Cursor.RowCount > 0) Then
        '    Log("GOT USER")
        '    ' Get fleet from SQLite table "reg"
        '    '        getFleet
        'End If
    Catch
        Log(LastException)
    End Try
End Sub

Edit: I prefer to use B4XPreferenceDialog
 
Upvote 0

Declan

Well-Known Member
Licensed User
Longtime User
Many, Many Thanks.
Just one thing:
Is it possible to only show "ToastMessageShow("You MUST enter your Username AND Password", False)"
when the "OK" is clicked?
As the code is now, the ToastMessage Shows on each keypress and this creates a problem as the ToastMessage is over the keyboard.

My Complete Code:
B4X:
Sub Process_Globals
    Public ActionBarHomeClicked As Boolean
    Type DBResult (Tag As Object, Columns As Map, Rows As List)
    Type DBCommand (Name As String, Parameters() As Object)
    Public const rdcLink As String = "http://165.73.xx.xxx:4001/rdc"
   
    Private xui As XUI
   
    Dim DB As SQL
    Dim DBFileDir As String = File.DirInternal
    Dim DBFileName As String = "iss.db"
   
    Dim currentUser As String
    Dim currentPwd As String
   
    Dim myUsername As String
    Dim myPassword As String
    Dim myFleet As String
End Sub

Sub Globals
    Private dialog As B4XDialog
    Private txtUsername As B4XFloatTextField
    Private txtPassword As B4XFloatTextField
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        DB.Initialize(DBFileDir, DBFileName, True)
    End If
    Dim pm As B4XPagesManager
    pm.Initialize(Activity)
   
   
End Sub

Sub CheckForUser
    Dim cursor As ResultSet  = DB.ExecQuery("SELECT * FROM reg")
    If cursor.RowCount <1 Then
        dialog.Initialize(Activity)
        dialog.Title = "Invictus Login"
   
        Dim currentUser As String
        Dim currentPwd  As String
   
        Dim p As B4XView = xui.CreatePanel("")
        p.SetLayoutAnimated(0, 0, 0, 300dip, 150dip)
        p.LoadLayout("CustomDialog")   'has both B4XFloatTextField
        dialog.PutAtTop = True
        Dim rs As ResumableSub = dialog.ShowCustom(p, "OK", "", "CANCEL")
        txtUsername.RequestFocusAndShowKeyboard
   
        IsDialogValid(txtUsername.Text, txtPassword.text)
        Wait For (rs) Complete (Result As Int)
        If Result = xui.DialogResponse_Positive Then
            currentUser = txtUsername.Text
            currentPwd = txtPassword.text
        End If
    Else
        Log("User is in the database")
    End If
    cursor.close
   
    If (cursor.RowCount > 0) Then
        Log("GOT USER")
'        getFleet
    End If
End Sub

Private Sub IsDialogValid (user As String, pwd As String)
    Dim ok As B4XView = dialog.GetButton(xui.DialogResponse_Positive)
    If user.Length > 0 And pwd.Length > 0 Then
        ok.Enabled = True
    Else
        ToastMessageShow("You MUST enter your Username AND Password", False)
        ok.Enabled = False
    End If
End Sub

Sub txtUsername_TextChanged (Old As String, New As String)
    If dialog.Visible = False Then Return
    IsDialogValid(New, txtPassword.Text)
End Sub

Sub txtPassword_TextChanged (Old As String, New As String)
    If dialog.Visible = False Then Return
    IsDialogValid(txtUsername.Text, New)
End Sub

Sub getUser (id As String)
    Dim req As DBRequestManager = CreateRequest
    Dim cmd As DBCommand = CreateCommand("get_user", Array(id))
    Wait For (req.ExecuteQuery(cmd, 0, Null)) JobDone(j As HttpJob)
    If j.Success Then
        req.HandleJobAsync(j, "req")
        Wait For (req) req_Result(res As DBResult)
        For Each row() As Object In res.Rows
            myUsername = row(res.Columns.Get("username"))
            myPassword = row(res.Columns.Get("password"))
            myFleet = row(res.Columns.Get("fleet"))
        Next
        Log("myUsername: " & myUsername)
        Log("myPassword: " & myPassword)
        Log("myFleet: " & myFleet)
    Else
        Log("ERROR: " & j.ErrorMessage)
    End If
    j.Release
   
    ' Check User
    If (myUsername = currentUser) Then
        Log("GOT User")  
               
    Else If (myUsername <> currentUser) Then
        Log("NO Username")
        txtUsername.Text = ""
        ToastMessageShow("Incorrect Username", False)
    End If
   
    'Check Password
    If (myPassword = currentPwd) Then
        Log("GOT Password")
    Else If (myPassword <> currentPwd) Then
        Log("NO Password")
        txtPassword.Text = ""
        ToastMessageShow("Incorrect Password", False)
    Else If (myPassword <> currentPwd) Then
    End If
   
    If (myUsername = currentUser) And (myPassword = currentPwd) Then
        dialog.Show($"   Welcome ${currentUser}"$, "OK", "", "")
        Log("Got Login")
        'Now Update MYSQL Table "users"
        regUser(myUsername)
        'Now Insert Into SQLite table "reg"
        insertUser
    End If
   
End Sub

Sub regUser (id As String)
    'sql.reg_user=UPDATE users SET datereg= regdate WHERE user = ?;
    Dim myDate As String
    DateTime.DateFormat="dd-MM-yyyy"
    myDate =DateTime.Date(DateTime.Now)
   
    Log("Date: " & myDate)
    Dim req As DBRequestManager = CreateRequest
    Dim cmd As DBCommand = CreateCommand("reg_user", Array (myDate,id))
    Dim j As HttpJob = CreateRequest.ExecuteBatch(Array(cmd), Null)
    Wait For (req.ExecuteCommand(cmd,Null)) JobDone(j As HttpJob)
    If j.Success Then
        Log("Update Successefull")
        ToastMessageShow("Registration Successful", False)
    Else
        Log("ERROR Update" & j.ErrorMessage)
    End If
    j.Release
End Sub

Sub insertUser
    DB.Initialize(DBFileDir, DBFileName, True)
    DB.ExecNonQuery2("INSERT INTO reg VALUES(?,?,?)", Array(myUsername, myPassword,myFleet))
End Sub

Sub CreateRequest As DBRequestManager
    Dim req As DBRequestManager
    req.Initialize(Me, rdcLink)
    Return req
End Sub

Sub CreateCommand(Name As String, Parameters() As Object) As DBCommand
    Dim cmd As DBCommand
    cmd.Initialize
    cmd.Name = Name
    If Parameters <> Null Then cmd.Parameters = Parameters
    Return cmd
End Sub
 
Upvote 0

teddybear

Well-Known Member
Licensed User
Many, Many Thanks.
Just one thing:
Is it possible to only show "ToastMessageShow("You MUST enter your Username AND Password", False)"
when the "OK" is clicked?
As the code is now, the ToastMessage Shows on each keypress and this creates a problem as the ToastMessage is over the keyboard.

My Complete Code:
B4X:
Sub Process_Globals
    Public ActionBarHomeClicked As Boolean
    Type DBResult (Tag As Object, Columns As Map, Rows As List)
    Type DBCommand (Name As String, Parameters() As Object)
    Public const rdcLink As String = "http://165.73.xx.xxx:4001/rdc"
  
    Private xui As XUI
  
    Dim DB As SQL
    Dim DBFileDir As String = File.DirInternal
    Dim DBFileName As String = "iss.db"
  
    Dim currentUser As String
    Dim currentPwd As String
  
    Dim myUsername As String
    Dim myPassword As String
    Dim myFleet As String
End Sub

Sub Globals
    Private dialog As B4XDialog
    Private txtUsername As B4XFloatTextField
    Private txtPassword As B4XFloatTextField
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        DB.Initialize(DBFileDir, DBFileName, True)
    End If
    Dim pm As B4XPagesManager
    pm.Initialize(Activity)
  
  
End Sub

Sub CheckForUser
    Dim cursor As ResultSet  = DB.ExecQuery("SELECT * FROM reg")
    If cursor.RowCount <1 Then
        dialog.Initialize(Activity)
        dialog.Title = "Invictus Login"
  
        Dim currentUser As String
        Dim currentPwd  As String
  
        Dim p As B4XView = xui.CreatePanel("")
        p.SetLayoutAnimated(0, 0, 0, 300dip, 150dip)
        p.LoadLayout("CustomDialog")   'has both B4XFloatTextField
        dialog.PutAtTop = True
        Dim rs As ResumableSub = dialog.ShowCustom(p, "OK", "", "CANCEL")
        txtUsername.RequestFocusAndShowKeyboard
  
        IsDialogValid(txtUsername.Text, txtPassword.text)
        Wait For (rs) Complete (Result As Int)
        If Result = xui.DialogResponse_Positive Then
            currentUser = txtUsername.Text
            currentPwd = txtPassword.text
        End If
    Else
        Log("User is in the database")
    End If
    cursor.close
  
    If (cursor.RowCount > 0) Then
        Log("GOT USER")
'        getFleet
    End If
End Sub

Private Sub IsDialogValid (user As String, pwd As String)
    Dim ok As B4XView = dialog.GetButton(xui.DialogResponse_Positive)
    If user.Length > 0 And pwd.Length > 0 Then
        ok.Enabled = True
    Else
        ToastMessageShow("You MUST enter your Username AND Password", False)
        ok.Enabled = False
    End If
End Sub

Sub txtUsername_TextChanged (Old As String, New As String)
    If dialog.Visible = False Then Return
    IsDialogValid(New, txtPassword.Text)
End Sub

Sub txtPassword_TextChanged (Old As String, New As String)
    If dialog.Visible = False Then Return
    IsDialogValid(txtUsername.Text, New)
End Sub

Sub getUser (id As String)
    Dim req As DBRequestManager = CreateRequest
    Dim cmd As DBCommand = CreateCommand("get_user", Array(id))
    Wait For (req.ExecuteQuery(cmd, 0, Null)) JobDone(j As HttpJob)
    If j.Success Then
        req.HandleJobAsync(j, "req")
        Wait For (req) req_Result(res As DBResult)
        For Each row() As Object In res.Rows
            myUsername = row(res.Columns.Get("username"))
            myPassword = row(res.Columns.Get("password"))
            myFleet = row(res.Columns.Get("fleet"))
        Next
        Log("myUsername: " & myUsername)
        Log("myPassword: " & myPassword)
        Log("myFleet: " & myFleet)
    Else
        Log("ERROR: " & j.ErrorMessage)
    End If
    j.Release
  
    ' Check User
    If (myUsername = currentUser) Then
        Log("GOT User") 
              
    Else If (myUsername <> currentUser) Then
        Log("NO Username")
        txtUsername.Text = ""
        ToastMessageShow("Incorrect Username", False)
    End If
  
    'Check Password
    If (myPassword = currentPwd) Then
        Log("GOT Password")
    Else If (myPassword <> currentPwd) Then
        Log("NO Password")
        txtPassword.Text = ""
        ToastMessageShow("Incorrect Password", False)
    Else If (myPassword <> currentPwd) Then
    End If
  
    If (myUsername = currentUser) And (myPassword = currentPwd) Then
        dialog.Show($"   Welcome ${currentUser}"$, "OK", "", "")
        Log("Got Login")
        'Now Update MYSQL Table "users"
        regUser(myUsername)
        'Now Insert Into SQLite table "reg"
        insertUser
    End If
  
End Sub

Sub regUser (id As String)
    'sql.reg_user=UPDATE users SET datereg= regdate WHERE user = ?;
    Dim myDate As String
    DateTime.DateFormat="dd-MM-yyyy"
    myDate =DateTime.Date(DateTime.Now)
  
    Log("Date: " & myDate)
    Dim req As DBRequestManager = CreateRequest
    Dim cmd As DBCommand = CreateCommand("reg_user", Array (myDate,id))
    Dim j As HttpJob = CreateRequest.ExecuteBatch(Array(cmd), Null)
    Wait For (req.ExecuteCommand(cmd,Null)) JobDone(j As HttpJob)
    If j.Success Then
        Log("Update Successefull")
        ToastMessageShow("Registration Successful", False)
    Else
        Log("ERROR Update" & j.ErrorMessage)
    End If
    j.Release
End Sub

Sub insertUser
    DB.Initialize(DBFileDir, DBFileName, True)
    DB.ExecNonQuery2("INSERT INTO reg VALUES(?,?,?)", Array(myUsername, myPassword,myFleet))
End Sub

Sub CreateRequest As DBRequestManager
    Dim req As DBRequestManager
    req.Initialize(Me, rdcLink)
    Return req
End Sub

Sub CreateCommand(Name As String, Parameters() As Object) As DBCommand
    Dim cmd As DBCommand
    cmd.Initialize
    cmd.Name = Name
    If Parameters <> Null Then cmd.Parameters = Parameters
    Return cmd
End Sub
As aeric said in post #3, switch B4xDialogs to B4XPreferenceDialog, it will be simpler
 
Upvote 0
Top