Android Question why not firing SQL Ready function?

gacar

Active Member
I am trying to mssql database with JSQL but JSQL ready function connot firing. Thanks

B4X:
'In Main page
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
    #AdditionalJar: jtds-1.3.1.jar
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

'#BridgeLogger: True

Sub Process_Globals
    'Public ActionBarHomeClicked As Boolean
End Sub

Sub Globals 
    Private Button1 As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
     Activity.LoadLayout("test2")
End Sub
 
Private Sub Button1_Click
    ConnectSQL.Connect
End Sub


B4X:
'In Code Page
Sub Process_Globals
    Dim SQL1 As SQL
#Region Database Location
    Dim DBLocation As String = "192.168.1.21:1433"
    Dim DBUsername As String = "UserName"
    Dim DBPassword As String = "Password"
#End Region
End Sub

Public Sub Connect
    SQL1.InitializeAsync("MSSQL","net.sourceforge.jtds.jdbc.Driver", $"jdbc:jtds:sqlserver://${DBLocation}/DemirHaber"$, DBUsername, DBPassword)
End Sub

Sub sql1_Ready (Success As Boolean) 'Here not firing
    Log(Success)
    If Success = False Then
        Log(LastException)
        Return
    End If
    Dim rs As ResultSet = SQL1.ExecQuery("SELECT table_name FROM information_schema.tables")
    Do While rs.NextRow
        Log(rs.GetString2(0))
    Loop
    rs.Close
End Sub
 
Solution
I found solution, now working well.
I was using an external emulator (Leapdroid). The whole problem was due to this reason.
The code runs smoothly when using the built-in emulator that comes with B4A.

gacar

Active Member
1. You should use JdbcSQL with B4A: https://www.b4x.com/android/forum/t...ly-connect-to-remote-databases.84016/#content
2. Static code modules can't handle events in B4A. Use a class instead.
3. Don't waste your time with activities. Switch to B4XPages.
Thanks for solution Erel.

I created new project on B4A "New > B4XPages"
I put the codes on the "B4XMainPage"
I used JdbcSQL but didn't work again.
I tried with JSQL but even didn't work.

I replaced your code in

but didn't work

I am not getting any error while compling and running

I changed your codes like as below

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
    #AdditionalJar: jtds-1.3.1.jar
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region
'#AdditionalJar: mysql-connector-java-5.1.34-bin
#BridgeLogger: true
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private ProgressBar1 As ProgressBar
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("1")

End Sub

Sub Activity_Click
    ProgressBar1.Visible = True
    Wait For (CallSub(Starter, "ListAnimals")) Complete (Result As Boolean)
    Log("Completed. Success: " & Result)
    ProgressBar1.Visible = False
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

In starter Code

B4X:
#Region  Service Attributes 
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Public MSSQL As JdbcSQL
    Private driver As String = "net.sourceforge.jtds.jdbc.Driver"
    Private jdbcUrl As String = "jdbc:jtds:sqlserver://192.168.1.21:1433/DemirHaber"
    Private Username As String = "UserName"
    Private Password As String = "Password"
End Sub

Sub Service_Create
    'need to disable it as reading from large JdbcResultSet will cause network requests to be sent on the main thread.
    DisableStrictMode
End Sub

Sub Service_Start (StartingIntent As Intent)

End Sub

Sub DisableStrictMode
    Dim jo As JavaObject
    jo.InitializeStatic("android.os.Build.VERSION")
    If jo.GetField("SDK_INT") > 9 Then
        Dim policy As JavaObject
        policy = policy.InitializeNewInstance("android.os.StrictMode.ThreadPolicy.Builder", Null)
        policy = policy.RunMethodJO("permitAll", Null).RunMethodJO("build", Null)
        Dim sm As JavaObject
        sm.InitializeStatic("android.os.StrictMode").RunMethod("setThreadPolicy", Array(policy))
    End If
End Sub

Sub Connect As ResumableSub
    MSSQL.InitializeAsync("MSSQL", driver, jdbcUrl, Username, Password)
    Wait For MSSQL_Ready (Success As Boolean)
    If Success = False Then
        Log("Check unfiltered logs for JDBC errors.")
    End If
    Return Success
End Sub

Sub CloseConnection
     MSSQL.Close
End Sub

Sub ListAnimals As ResumableSub
    Wait For (Connect) Complete (Success As Boolean)
    If Success Then
        Try
            Dim sf As Object = MSSQL.ExecQueryAsync("MSSQL", "SELECT id FROM Insaat_Demiri", Array(300))
            Wait For (sf) MSSQL_QueryComplete (Success As Boolean, Crsr As JdbcResultSet)
            If Success Then
                Do While Crsr.NextRow
                    Log($"Id: ${Crsr.GetInt("id")}, Name: ${Crsr.GetString("name")}"$)
                Loop
                Crsr.Close
            End If
        Catch
            Success = False
            Log(LastException)
        End Try
        CloseConnection
    End If
    Return Success
End Sub

Sub Service_TaskRemoved
    'This event will be raised when the user removes the app from the recent apps list.
End Sub

'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub Service_Destroy

End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Many mistakes.

1. Don't use the starter service with B4XPages. It works but you are just making things more complicated than they need to be.
2. You have set the event name parameter to MSSQL. This means that the event sub name should be MSSQL_Ready:
3. Calling SQL.InitializeAsync and then immediately Close makes no sense.

Correct code:
B4X:
SQL.InitializeAsync("SQL","net.sourceforge.jtds.jdbc.Driver", $"jdbc:jtds:sqlserver://${DBLocation}/DemirHaber"$, DBUsername, DBPassword)
Wait For SQL_Ready (Success As Boolean)
Log(Success)
If Success Then
Dim rs As JdbcResultSet = SQL.execquery("select table_name from information_schema.tables")
    Do While rs.nextrow
        Log(rs.getstring2(0))
    Loop
    rs.close
    SQL.Close
End If
 
Upvote 0

gacar

Active Member
Many mistakes.

1. Don't use the starter service with B4XPages. It works but you are just making things more complicated than they need to be.
2. You have set the event name parameter to MSSQL. This means that the event sub name should be MSSQL_Ready:
3. Calling SQL.InitializeAsync and then immediately Close makes no sense.

Correct code:
B4X:
SQL.InitializeAsync("SQL","net.sourceforge.jtds.jdbc.Driver", $"jdbc:jtds:sqlserver://${DBLocation}/DemirHaber"$, DBUsername, DBPassword)
Wait For SQL_Ready (Success As Boolean)
Log(Success)
If Success Then
Dim rs As JdbcResultSet = SQL.execquery("select table_name from information_schema.tables")
    Do While rs.nextrow
        Log(rs.getstring2(0))
    Loop
    rs.close
    SQL.Close
End If

Thank you for patiently answering my questions. I will create a project step by step below, can you tell me in which step I made a mistake?

On B4A
1- "New > B4XPages"
2- Add "JdbcSQL" from Library manager.
3- Disable Button1_Click event in "B4XMainpage"
4-Modifiying "Main Page" code like as below

B4X:
#Region  Project Attributes 
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName: 
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
    #AdditionalJar: jtds-1.3.1.jar
#End Region

#Region  Activity Attributes 
    #FullScreen: False
    #IncludeTitle: True
#End Region

'#BridgeLogger: True

Sub Process_Globals
    Public ActionBarHomeClicked As Boolean
    Public SQL As JdbcSQL

#Region Database Location
    Private DBLocation As String = "192.168.1.21:1433" 'Can use IP address or domain name
    Private DBUsername As String = "UserName"
    Private DBPassword As String = "Password"
#End Region
End Sub

Public Sub SQLConnect
    SQL.InitializeAsync("SQL","net.sourceforge.jtds.jdbc.Driver", $"jdbc:jtds:sqlserver://${DBLocation}/DemirHaber"$, DBUsername, DBPassword)
    Wait For SQL_Ready (Success As Boolean)
    Log(Success)
    If Success Then
        Dim rs As JdbcResultSet = SQL.execquery("select table_name from information_schema.tables")
        Do While rs.nextrow
            Log(rs.getstring2(0))
        Loop
        rs.close
        SQL.Close
    End If
End Sub

Sub SQL_Ready (Success As Boolean)
    Log(Success)
    If Success = False Then
        Log(LastException)
        Return
    End If
    Dim rs As JdbcResultSet = SQL.execquery("select table_name from information_schema.tables")
    Do While rs.nextrow
        Log(rs.getstring2(0))
    Loop
    rs.close
End Sub

Sub Globals

    Private Button1 As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    
    Dim pm As B4XPagesManager
    pm.Initialize(Activity)
    Activity.LoadLayout("MainPage")
End Sub

'Template version: B4A-1.01
#Region Delegates

Sub Activity_ActionBarHomeClick
    ActionBarHomeClicked = True
    B4XPages.Delegate.Activity_ActionBarHomeClick
    ActionBarHomeClicked = False
End Sub

Sub Activity_KeyPress (KeyCode As Int) As Boolean
    Return B4XPages.Delegate.Activity_KeyPress(KeyCode)
End Sub

Sub Activity_Resume
    B4XPages.Delegate.Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    B4XPages.Delegate.Activity_Pause
End Sub

Sub Activity_PermissionResult (Permission As String, Result As Boolean)
    B4XPages.Delegate.Activity_PermissionResult(Permission, Result)
End Sub

Sub Create_Menu (Menu As Object)
    B4XPages.Delegate.Create_Menu(Menu)
End Sub

#if Java
public boolean _onCreateOptionsMenu(android.view.Menu menu) {
     processBA.raiseEvent(null, "create_menu", menu);
     return true;
    
}
#End If
#End Region

'Program code should go into B4XMainPage and other pages.

Private Sub Button1_Click
    'MsgboxAsync("Hello world!", "B4X")
    SQLConnect
End Sub

3- Disable
 
Upvote 0

gacar

Active Member
The complete code is wrong.

1. Don't add anything to the main module, except of the #AdditionalJar attribute.
2. See the code I posted above.


Finally worked thanks. But i have a problem still.

B4X:
    Private DBLocation As String = "LAPTOP-URFS4BPE" '<====== If i use this then fired but not success connection
    'I have (UnknownHostException) java.net.UnknownHostException: Host is unresolved: LAPTOP-URFS4BPE error.
    'But in B4J project same code getting success connection
 

    Private DBLocation As String = "192.168.1.21:1433"  '<====== If I use this not firing and not any error message
   'But in B4J project same code getting success connection too

Complate code below


B4X:
#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip

Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Public SQL As JdbcSQL
#Region Database Location
    Private DBLocation As String = "LAPTOP-URFS4BPE" '<====== If i use this then fired but not success connection
    'I have (UnknownHostException) java.net.UnknownHostException: Host is unresolved: LAPTOP-URFS4BPE error.
    'But in B4J project same code getting success connection
 
    'Private DBLocation As String = "192.168.1.21:1433" '<====== If I use this not firing and not any error message
    'But in B4J project same code getting success connection too

    Private DBUsername As String = "UserName"
    Private DBPassword As String = "Password"
#End Region
    Private Button1 As Button
End Sub

Public Sub SQLConnect
    SQL.InitializeAsync("SQL","net.sourceforge.jtds.jdbc.Driver", $"jdbc:jtds:sqlserver://${DBLocation}/DemirHaber"$, DBUsername, DBPassword)

'    wait for jSQL_Ready (success As Boolean)
'    Log(success)
'    If success Then
'        Dim rs As JdbcResultSet = jSQL.execquery("select table_name from information_schema.tables")
'        Do While rs.nextrow
'            Log(rs.getstring2(0))
'        Loop
'        rs.close
'        jSQL.close
'    End If
End Sub
 
 
Sub SQL_Ready (Success As Boolean)
    Log(Success)
    If Success = False Then
        Log(LastException)
        Return
    End If
    Dim rs As JdbcResultSet =  SQL.execquery("select table_name from information_schema.tables")
    Do While rs.nextrow
        Log(rs.getstring2(0))
    Loop
    rs.close
End Sub

Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Private Sub Button1_Click
    'Qxui.MsgboxAsync("Hello world!", "B4X")
    SQLConnect
End Sub
 
Last edited:
Upvote 0

gacar

Active Member
I found solution, now working well.
I was using an external emulator (Leapdroid). The whole problem was due to this reason.
The code runs smoothly when using the built-in emulator that comes with B4A.
 
Upvote 0
Solution
Top