Android Question Remote server connection how to port B4J code (working) to B4A (SQL.InitializeAsync)

Diego Marcelo Croatto

Member
Licensed User
Longtime User
Hi to all programmers.
I have a MariaDB server working in a Rasberry Pi (all Ok)
I tested the folow code to get data over Wifi from my PC in B4J and works fine.
I need port it to Android and I have problems with the connection and some libraries can ayone help me?.... Thank's a lot ;)

The log Result is:

Captura de pantalla 2024-06-29 194409.jpg



The working code in B4J its simple as....

Get remote data from MariaDB Server:
'Non-UI application (console / server application)
#Region Project Attributes
    #CommandLineArgs:
    #MergeLibraries: True
#End Region

    'MariaDB Connector/J Driver
    #AdditionalJar: mariadb-java-client-2.4.2.jar

Sub Process_Globals
    Private SQL As SQL
    Dim RS As ResultSet
    
#Region Database Location
    Private DBLocation As String = "192.168.xxx.xxx:1818" '<-- IP address
    Private DBUsername As String = "user" '<-- DB user name
    Private DBPassword As String = "123456" '<-- DB password
    Private SQLCommand As String            '<-- Auxiliar string to see the text
    
#End Region
End Sub

Sub AppStart (Args() As String)

    LogError("---------- NorthWind Database (MariaDB) ----------")
    SQLCommand=$"jdbc:mariadb://${DBLocation}:3306/"$                         
    SQL.InitializeAsync("MariaDB", "org.mariadb.jdbc.Driver",SQLCommand , DBUsername, DBPassword)
    SQL.Close
    StartMessageLoop 'only required in a console app

End Sub

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

'Connected to MariaDB SQL Server
Sub MariaDB_Ready (Success As Boolean)
    
    If Success Then
        RS = SQL.ExecQuery("SELECT x.* FROM TabletsDB.Calibracion x")
        
        Do While RS.NextRow
            Log(RS.GetString2(0)) 'First register
            Log(RS.GetString2(1))
            Log(RS.GetString2(2))
            Log(RS.GetString2(3))
            Log(RS.GetString2(4))
            Log(RS.GetString2(5))
            Log(RS.GetString2(6))
            Log(RS.GetString2(7)) 'Last register
        Loop
        
        RS.Close
        
    End If
    StopMessageLoop 'only required in a console app
End Sub
 

Diego Marcelo Croatto

Member
Licensed User
Longtime User
Well... I try a lot of time and nothing.... in left monitor I test the B4A code with JdbcSQL (not working) and in the right monitor the B4J code with JSQL library (the reference working OK)

Both (B4A and B4J) are the same additional line
#AdditionalJar:
#AdditionalJar: mariadb-java-client-2.4.2.jar
The B4J Connection code (working)
B4J MariaDB server connection code:
    SQLCommand="jdbc:mariadb://192.168.1.59:3306/"                         
    SQL.InitializeAsync("MariaDB", "org.mariadb.jdbc.Driver",SQLCommand , DBUsername, DBPassword)
    SQL.Close
And the B4A Connection code (not working)
B4A MariaDB connection code:
    SQLCommand="jdbc:mariadb://192.168.1.59:3306/"                        
    sql1.InitializeAsync("MariaDB", "org.mariadb.jdbc.Driver",SQLCommand , DBUsername, DBPassword)
    sql1.Close

And the same Sub for read one row with 8 columns
Result Database:
'Connected to MariaDB SQL Server
Sub MariaDB_Ready (Success As Boolean)
    If Success Then
        RS = sql1.ExecQuery("SELECT x.* FROM TabletsDB.Calibracion x")
        Do While RS.NextRow
            Log(RS.GetString2(0))
            Log(RS.GetString2(1))
            Log(RS.GetString2(2))
            Log(RS.GetString2(3))
            Log(RS.GetString2(4))
            Log(RS.GetString2(5))
            Log(RS.GetString2(6))
            Log(RS.GetString2(7))
        Loop
        RS.Close
    End If
End Sub

This is the connection results (Debugging) of B4A in sql1 --> Connection is null (all is null)
1719796455962.png

This is the connection results (Debugging) of B4J in SQL --> Connection is with data
1719796691233.png


What I do wrong?.... what is the error in the Android platform? The WiFi connection its Ok between the android device and the DB server.
Thank's a lot for the help.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
What is the purpose of this strange code:
B4X:
SQLCommand="jdbc:mariadb://192.168.1.59:3306/"                        
    sql1.InitializeAsync("MariaDB", "org.mariadb.jdbc.Driver",SQLCommand , DBUsername, DBPassword)
    sql1.Close
?

Post the output of this code:
B4X:
sql1.InitializeAsync("MariaDB", "org.mariadb.jdbc.Driver",SQLCommand , DBUsername, DBPassword)
 Wait For MariaDB_Ready (Success As Boolean)
 Log(Success & ": " & LastException)
sql1.Close
 
Upvote 0

Diego Marcelo Croatto

Member
Licensed User
Longtime User
? Erel I'm sorry ... the strange code is for explain why I can't connect form android devices to the remote database. But it seems that my explanation was not clear enough.
The idea is to connect from a tablets (android) to remote intranet database server (raspberry pi) for register the data sended from the tablets.
Raspberry Pi is a economical way to mount a server (mariadb/mysql) with minimal recurses lot off storage and access it from many ways to the data stored.

SQLCommand is for the debugger and the purpose is to see if the string to be sent is correct.

I try to explain:
I write the code in B4J and works ok with this libraries:
B4J:
    Private SQL As SQL
    Dim RS As ResultSet
I write the same code in B4A and not connect to database with this libraries:
B4A:
    Dim sql1 As JdbcSQL
    Dim RS As JdbcResultSet

I cant find the code portability between B4J and B4A.
 
Upvote 0

Culjko

Member
Hello,
I have Android tablet and Android Pos Sunmi V2 wich work on same sql server, Andorid tablet works normaly but android pos not, i try your code and its same problem but when i change code sql.Initialize("org.mariadb.jdbc.Driver",SQLCommand & "?characterEncoding=utf8;username=****;password=*****;") i get this error:
B4X:
java.sql.SQLInvalidAuthorizationSpecException: Access denied for user 'root'@'79-101-142-240.dynamic.isp.telekom.rs' (using password: NO)
    at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:238)
    at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:171)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.connectWithoutProxy(AbstractConnectProtocol.java:1132)
    at org.mariadb.jdbc.internal.util.Utils.retrieveProxy(Utils.java:561)
    at org.mariadb.jdbc.MariaDbConnection.newConnection(MariaDbConnection.java:175)
    at org.mariadb.jdbc.Driver.connect(Driver.java:92)
    at java.sql.DriverManager.getConnection(DriverManager.java:569)
    at java.sql.DriverManager.getConnection(DriverManager.java:219)
    at anywheresoftware.b4j.objects.SQL.Initialize2(SQL.java:56)
    at anywheresoftware.b4j.objects.SQL.Initialize(SQL.java:45)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runVoidMethod(Shell.java:777)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:354)
    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.BA.raiseEvent2(BA.java:205)
    at anywheresoftware.b4a.debug.Debug.delegate(Debug.java:262)
    at com.eVirtual.Listener.main._startmariaserver(main.java:547)
    at com.eVirtual.Listener.main._activity_create(main.java:422)
    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 com.eVirtual.Listener.main.afterFirstLayout(main.java:105)
    at com.eVirtual.Listener.main.access$000(main.java:17)
    at com.eVirtual.Listener.main$WaitForLayout.run(main.java:83)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6121)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: java.sql.SQLException: Access denied for user 'root'@'79-101-142-240.dynamic.isp.telekom.rs' (using password: NO)
    at org.mariadb.jdbc.internal.protocol.AbstractConnectProtocol.authentication(AbstractConnectProtocol.java:855)

obviously is to connection is blocked, maybe you shold sovle problem on server. I will try to do it and i write it here.
 
Upvote 0

Culjko

Member
maybe i was wrong :)

class mySQL
B4X:
Sub Class_Globals
    Public mySQL As SD_SQL
    Private recordSet As SD_ResultSet
    
    Dim UserName As String
    Dim Password As String
    Dim Driver As String = "org.mariadb.jdbc.Driver"
    Dim SQLServer As String = "127.0.0.1"
    
    Dim LastRecord As Double
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize(CallbackModule As Object, EventName As String)
    mySQL.Initialize(CallbackModule,EventName)
    recordSet.Initialize("")
End Sub

Public Sub connect(DataBase As String)

    Log($"jdbc:mariadb://${SQLServer}/${DataBase}"$)
    Try
        mySQL.Connect(Driver, $"jdbc:mariadb://${SQLServer}/${DataBase}"$, UserName, Password)
        ProgressDialogShow("connecting SQL")
        Wait For SQL_Ready(Success As Boolean)
    Catch
        Log(LastException)
    End Try
    
End Sub






Public Sub selectSQL(sqlStr As String)
    Log("sql execute")
    recordSet = mySQL.ExecQuery(sqlStr)
    recordSet.last
    LastRecord = recordSet.GetRow
    recordSet.First
End Sub


Public Sub moveNext
    Return recordSet.NextRow
End Sub

Public Sub movePrevious
    Return recordSet.PreviousRow
End Sub

Public Sub moveFirst
    recordSet.First
End Sub

Public Sub moveLast
    recordSet.last
End Sub

Public Sub RowCount
    
    Log(recordSet.relativeRow(-1))
End Sub


Public Sub eof
    Return IIf(recordSet.GetRow = LastRecord, True, False)
End Sub


Public Sub bof
    Return IIf(recordSet.GetRow = 1 Or recordSet.GetRow = 0, True, False)
End Sub

Public Sub GetString(Field As String)
    Return recordSet.GetString(Field)
End Sub

Public Sub GetInt(Field As String)
    Return recordSet.GetInt(Field)
End Sub

Public Sub GetDouble(Field As String)
    Return recordSet.GetDouble(Field)
End Sub

Public Sub GetRow As Int
    Return recordSet.GetRow
End Sub



Sub mySQL_Ready (Success As Boolean)
    
    Log("sql ready")
    
    
    If Success Then
            Log("MSSQL_Ready")
        
    End If
    
    
    Log(Success)
    
    
End Sub

on andorid 14 and 11 work properly



on android 7.1.2 not work

B4X:
jdbc:mariadb://82.117.222.18:3306/esir
Error occurred on line: 36 (SD_SQL)
java.lang.ClassCastException: java.lang.NoClassDefFoundError cannot be cast to java.lang.Exception
    at anywheresoftware.b4a.BA.setLastException(BA.java:662)
    at com.eVirtual.Listener.mysql$ResumableSub_connect.resume(mysql.java:157)
    at com.eVirtual.Listener.mysql._connect(mysql.java:68)
    at com.eVirtual.Listener.main._activity_create(main.java:436)
    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 com.eVirtual.Listener.main.afterFirstLayout(main.java:105)
    at com.eVirtual.Listener.main.access$000(main.java:17)
    at com.eVirtual.Listener.main$WaitForLayout.run(main.java:83)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6121)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
** Activity (main) Resume **

all is same but diferent android version
 
Upvote 0
Top