Android Question java.lang.reflect.InvocationTargetException

bfw

Member
Hi @ all,

I have two methods implement to connect to a MariaDB

Code:
Sub ConnectToMariaDB(jdbcURL As String, username As String, password As String) As JavaObject
    Dim driver As JavaObject
    driver.InitializeNewInstance("org.mariadb.jdbc.Driver", Null)
    Dim connection As JavaObject = driver.RunMethod("connect", Array(jdbcURL, CreateCredentials(username, password)))
    Return connection
End Sub

Sub CreateCredentials(username As String, password As String) As JavaObject
    Dim properties As JavaObject
    properties.InitializeNewInstance("java.util.Properties", Null)
    properties.RunMethod("setProperty", Array("user", username))
    properties.RunMethod("setProperty", Array("password", password))
    Return properties
End Sub

I call this like
Code:
'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    ...
    
    Try
        Dim jdbcURL As String = "jdbc:mariadb://localhost/bfw"
        sqlConnection = ConnectToMariaDB(jdbcURL, "bfw", "bfw")
    Catch
        Log(LastException)
    End Try
End Sub

When I run my program, the following exception is thrown
B4X:
Error occurred on line: 115 (B4XMainPage)
java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:132)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:732)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:348)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:157)
    at anywheresoftware.b4a.debug.Debug.delegate(Debug.java:262)
    at b4a.program.b4xmainpage._connecttomariadb(b4xmainpage.java:101)
    at b4a.program.b4xmainpage._b4xpage_created(b4xmainpage.java:86)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.debug.Debug.CallSub4(Debug.java:318)
    at anywheresoftware.b4a.debug.Debug.CallSubNew2(Debug.java:285)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.keywords.Common.CallSubDebug2(Common.java:1087)
    at b4a.program.b4xpagesmanager._createpageifneeded(b4xpagesmanager.java:1068)
    at b4a.program.b4xpagesmanager._showpage(b4xpagesmanager.java:425)
    at b4a.program.b4xpagesmanager._addpage(b4xpagesmanager.java:245)
    at b4a.program.b4xpagesmanager._addpageandcreate(b4xpagesmanager.java:259)
    at b4a.program.b4xpagesmanager._initialize(b4xpagesmanager.java:165)
    at b4a.program.main._activity_create(main.java:415)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:732)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:351)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:157)
    at b4a.program.main.afterFirstLayout(main.java:105)
    at b4a.program.main.access$000(main.java:17)
    at b4a.program.main$WaitForLayout.run(main.java:83)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.sql.SQLNonTransientConnectionException: Socket fail to connect to localhost. failed to connect to localhost/127.0.0.1 (port 3306) from /127.0.0.1 (port 32864) after 30000ms: isConnected failed: ECONNREFUSED (Connection refused)
    at org.mariadb.jdbc.client.impl.ConnectionHelper.connectSocket(ConnectionHelper.java:131)
    at org.mariadb.jdbc.client.impl.StandardClient.<init>(StandardClient.java:127)
    at org.mariadb.jdbc.Driver$$ExternalSyntheticLambda1.apply(D8$$SyntheticClass:0)
    at org.mariadb.jdbc.Driver.connect(Driver.java:73)
    at org.mariadb.jdbc.Driver.connect(Driver.java:102)
    at org.mariadb.jdbc.Driver.connect(Driver.java:27)
    ... 38 more
Caused by: java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 3306) from /127.0.0.1 (port 32864) after 30000ms: isConnected failed: ECONNREFUSED (Connection refused)
    at libcore.io.IoBridge.isConnected(IoBridge.java:278)
    at libcore.io.IoBridge.connectErrno(IoBridge.java:187)
    at libcore.io.IoBridge.connect(IoBridge.java:129)
    at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
    at java.net.Socket.connect(Socket.java:621)
    at org.mariadb.jdbc.client.impl.ConnectionHelper.connectSocket(ConnectionHelper.java:118)
    ... 43 more
Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
    at libcore.io

Knows anybody what's wrong?
 

bfw

Member
Hi Erel,

thank you for your reply. I tried to adapt the program to MariaDB, but unfortunately without success. I always only get to the message "Connecting to database is being established" and then the program seems to hang in an endless loop.

Starter.bas:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Public mysql As JdbcSQL
    Private driver As String = "com.mariadb.jdbc.Driver"
    Private jdbcUrl As String = "jdbc:mariadb://192.168.178.98/test"
    Private Username As String = "test"
    Private Password As String = "test"
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
    mysql.InitializeAsync("mariadb", driver, jdbcUrl, Username, Password)
    Log("Connecting to database is being established...")
    Wait For MySQL_Ready (Success As Boolean)
    Log(Success)
    If Success = False Then
        Log("Check unfiltered logs for JDBC errors.")
    End If
    Return Success
End Sub

Sub CloseConnection
     mysql.Close
End Sub

Sub ListAnimals As ResumableSub
    Wait For (Connect) Complete (Success As Boolean)
'    Log("Verbindung zur Datenbank wird aufgebaut ...")
    If Success Then
        Log("Connection successfully established")
        Log("Execute query...")
        Try
            Dim sf As Object = mysql.ExecQueryAsync("mariadb", "SELECT continent_id, name FROM continents WHERE continent_id > ?", Array(300))
            Wait For (sf) mysql_QueryComplete (Success As Boolean, Crsr As JdbcResultSet)
            If Success Then
                Do While Crsr.NextRow
                    Log($"Id: ${Crsr.GetInt("continent_id")}, Name: ${Crsr.GetString("name")}"$)
                Loop
                Crsr.Close
            End If
        Catch
            Log("Error executing the query")
            Success = False
            Log(LastException)
        End Try
        Log("Connection closed")
        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

I copied the file mariadb-java-client-3.5.1.jar into the subdirectory AdditionalLibraries\B4A and replaced the line
B4X:
#AdditionalJar: mysql-connector-java-5.1.34-bin
with
B4X:
#AdditionalJar: mariadb-java-client-3.5.1.jar

Unfortunately it doesn't work yet. A connection to the database cannot be established. Do you have any idea what the problem could be?
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Last edited:
Upvote 0
Top