Android Question Thread Exception

ferpahud

Active Member
Licensed User
Hello good day,

I'm trying to load some data from a table to a database online.

When I try to do this I get the following error:
"An error has occurred in sub:sincronizar_hc_responsesuccess
android.os.NetworkOnMainThreadException"

This is the code that loads data:

B4X:
Sub btnCargarPedidos_Click
    Dim req As HttpRequest
    Dim Query As String
    Dim id As Int
    Dim fecha As String
    Dim idCliente As Int
    Dim usuarioEmpleado As String
    Dim estado As String

    c=s.ExecQuery("SELECT * FROM pedido")
   
    If c.RowCount>0 Then
    For i=0 To c.RowCount-1
        c.Position=i
       
        id=c.GetString("id")
        fecha=c.GetString("fecha")
        idCliente=c.GetString("idCliente")
        usuarioEmpleado=c.GetString("usuarioEmpleado")
        estado=c.GetString("estado")
       
        Query="INSERT INTO Pedido (id, fecha, idCliente, usuarioEmpleado, estado) VALUES ('" & id & "','" & fecha & "','" & idCliente & "','" & usuarioEmpleado & "','" & estado & "')"
        req.InitializePost2("http://167.250.5.13/~distribuidora/paises.php", Query.GetBytes("UTF8"))
        hc.Execute(req, 1)
    Next
    End If
End Sub

Someone could help me? Thank you
 

ferpahud

Active Member
Licensed User
Just to make sure you did not forget to call it .
This is the code:
B4X:
#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim hc As HttpClient
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.
    Dim s As SQL
    Dim c As Cursor

    Private btnCargarPedidos As Button
    Private lblSincronizar As Label
  
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    If FirstTime Then
    hc.Initialize("hc")
    End If
  
    Dim ruta As String
    ruta=DBUtils.CopyDBFromAssets("distribuidora.db")
    s.Initialize(ruta,"distribuidora.db",True)
  
    Activity.LoadLayout("Sincronizar")

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

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 btnCargarPedidos_Click
    Dim req As HttpRequest
    Dim Query As String
    Dim id As Int
    Dim fecha As String
    Dim idCliente As Int
    Dim usuarioEmpleado As String
    Dim estado As String

    c=s.ExecQuery("SELECT * FROM pedido")
  
    If c.RowCount>0 Then
    For i=0 To c.RowCount-1
        c.Position=i
      
        id=c.GetString("id")
        fecha=c.GetString("fecha")
        idCliente=c.GetString("idCliente")
        usuarioEmpleado=c.GetString("usuarioEmpleado")
        estado=c.GetString("estado")
      
        Query="INSERT INTO Pedido (id, fecha, idCliente, usuarioEmpleado, estado) VALUES ('" & id & "','" & fecha & "','" & idCliente & "','" & usuarioEmpleado & "','" & estado & "')"
        req.InitializePost2("http://167.250.5.13/paises.php", Query.GetBytes("UTF8"))
        hc.Execute(req, 1)
    Next
    End If
End Sub

Sub hc_ResponseSuccess (Response As HttpResponse, tarea As Int)
Dim resultString As String
resultString = Response.GetString("UTF8")

Msgbox("Los datos han sido almacenados", "Éxito de operación")
End Sub

Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, tarea As Int)
Log("Error: " & Reason & ", StatusCode: " & StatusCode)
If Response <> Null Then
Log(Response.GetString("UTF8"))
Response.Release
End If
End Sub
 
Upvote 0

somed3v3loper

Well-Known Member
Licensed User
Longtime User
Add a call to the sub inside Activity_Create sub like this
B4X:
Sub Activity_Create(FirstTime As Boolean)
    DisableStrictMode
    ......
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
- Replace httprequest with okHTTP(utils)
- Dim a new httpjob Inside your loop for each job you want to execute
 
Upvote 0

ferpahud

Active Member
Licensed User
i can not believe you did not found anything

Did you used the search????

https://www.b4x.com/android/forum/pages/results/?query=httputil&page=1&prefix=8
<br class="Apple-interchange-newline"><div id="inner-editor"></div>

If I use the search engine.
I can not find how to replace:
B4X:
Sub hc_ResponseSuccess (Response As HttpResponse, tarea As Int)
Dim resultString As String
resultString = Response.GetString("UTF8")

Msgbox("Los datos han sido almacenados", "Éxito de operación")
End Sub

Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, tarea As Int)
Log("Error: " & Reason & ", StatusCode: " & StatusCode)
If Response <> Null Then
Log(Response.GetString("UTF8"))
Response.Release
End If
End Sub
 
Upvote 0

ferpahud

Active Member
Licensed User
see the httputils tutorial! I already wrote that in #13

You can get the result in sub JobDone

https://www.b4x.com/android/forum/t...-services-are-now-even-simpler.18992/#content

Is that so? because now not load any data:
B4X:
Sub btnCargarPedidos_Click
    Dim Query As String
    Dim id As Int
    Dim fecha As String
    Dim idCliente As Int
    Dim usuarioEmpleado As String
    Dim estado As String

    c=s.ExecQuery("SELECT * FROM pedido")
   
    If c.RowCount>0 Then
    For i=0 To c.RowCount-1
        c.Position=i
        Dim hc As HttpJob
        Dim req As HttpJob
        hc.Initialize("hc", Me)
        id=c.GetString("id")
        fecha=c.GetString("fecha")
        idCliente=c.GetString("idCliente")
        usuarioEmpleado=c.GetString("usuarioEmpleado")
        estado=c.GetString("estado")
       
        Query="INSERT INTO Pedido (id, fecha, idCliente, usuarioEmpleado, estado) VALUES ('" & id & "','" & fecha & "','" & idCliente & "','" & usuarioEmpleado & "','" & estado & "')"
        req.Initialize("http://167.250.5.13/paises.php", Query.GetBytes("UTF8"))
    Next
    End If
End Sub

Sub JobDone (Job As HttpJob)
   Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
   If Job.Success = True Then
      Select Job.JobName
         Case "Job1", "Job2"
            'print the result to the logs
            Log(Job.GetString)
         Case "Job3"
            'show the downloaded image
            Activity.SetBackgroundImage(Job.GetBitmap)
      End Select
   Else
      Log("Error: " & Job.ErrorMessage)
      ToastMessageShow("Error: " & Job.ErrorMessage, True)
   End If
    Job.Release
End Sub
 
Upvote 0
Top