Android Question java.lang.reflect.InvocationTargetException

Angelo Messina

Active Member
Licensed User
Longtime User
Hi everyone, I can't understand why
in debug it works but once compiled on device it generates this java.lang.reflect.InvocationTargetException error
 

Attachments

  • Screenshot (13).png
    Screenshot (13).png
    32.5 KB · Views: 39

Brian Dean

Well-Known Member
Licensed User
Longtime User
Why do you think that there is some connection between the error message and the screenshot that you have posted? And when you say "once compiled on device" do you mean running in Release mode? And if so what is the full error message?
 
Upvote 0

Angelo Messina

Active Member
Licensed User
Longtime User
Why do you think that there is some connection between the error message and the screenshot that you have posted? And when you say "once compiled on device" do you mean running in Release mode? And if so what is the full error message?
Logger connesso a: Xiaomi M2007J3SG
--------- beginning of main
running waiting messages (1)
** Activity (main) Resume **
** Activity (main) Create (first time) **
** Activity (main) Resume **
*** Receiver (httputils2service) Receive (first time) ***
(Http client initialized with accept all option.)
JobName = job4, Success = true
main_creaweb (java line: 1651)
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:132)
at com.DataLogger.fotovoltaico.main._creaweb(main.java:1651)
at com.DataLogger.fotovoltaico.main._loadtable(main.java:2577)
at com.DataLogger.fotovoltaico.main._b4xtable1_cellclicked(main.java:1114)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:221)
at anywheresoftware.b4a.keywords.Common.CallSub4(Common.java:1114)
at anywheresoftware.b4a.keywords.Common.CallSubNew3(Common.java:1077)
at com.DataLogger.fotovoltaico.b4xtable$ResumableSub_CellClicked.resume(b4xtable.java:638)
at com.DataLogger.fotovoltaico.b4xtable._cellclicked(b4xtable.java:409)
at com.DataLogger.fotovoltaico.b4xtable._lbl_click(b4xtable.java:2002)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:221)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:201)
at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:80)
at android.view.View.performClick(View.java:7753)
at android.view.View.performClickInternal(View.java:7730)
at android.view.View.access$3700(View.java:861)
at android.view.View$PerformClick.run(View.java:29146)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:210)
at android.os.Looper.loop(Looper.java:299)
at android.app.ActivityThread.main(ActivityThread.java:8293)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1045)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1668)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
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:646)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:182)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:145)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
at com.DataLogger.fotovoltaico.main.GetData(main.java:3541)
... 28 more
java.lang.reflect.InvocationTargetException
 
Upvote 0

Brian Dean

Well-Known Member
Licensed User
Longtime User
Do you have a subroutine called "creaweb"? If so it looks to be where the error occurs. Add some Log statements so that you can locate it. Even better, post some code so that people can understand what you are trying to achieve and where you might be going wrong.
 
Upvote 0

Angelo Messina

Active Member
Licensed User
Longtime User
Do you have a subroutine called "creaweb"? If so it looks to be where the error occurs. Add some Log statements so that you can locate it. Even better, post some code so that people can understand what you are trying to achieve and where you might be going wrong.
B4X:
Sub CreaWeb(Tipo As String)

    IndiceGenerale = asJava(Me).RunMethod("GetData",Array(url,"ID","-1"))
    Private HtmlCSS As String = $"
        table {width: 100%;border: 1px solid #cef;text-align: left; }
        th { font-weight: bold;    background-color: #acf;    border-bottom: 1px solid #cef; }
        td,th {    padding: 4px 5px; }
        .odd {background-color: #def; } 
        .odd td {border-bottom: 1px solid #cef; }
        a { text-decoration:none; color: #000;}"$        
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append("<html><body>").Append(CRLF)
    sb.Append("<style type='text/css'>").Append(HtmlCSS).Append("</style>").Append(CRLF)
    sb.Append("<table><thead><tr>").Append(CRLF)
    sb.Append("<th>").Append("Anno").Append("</th>")
    sb.Append("<th>").Append("Mese").Append("</th>")
    sb.Append("<th>").Append("Giorno").Append("</th>")
    sb.Append("<th>").Append("Kwh").Append("</th>")
    sb.Append("</thead>")
    sb.Append("</tr>").Append(CRLF)
    Dim row As Int
    For Each colroot As Map In PrendiKwhProdotti(Tipo)
        Dim anno As String = colroot.Get("anno")
        Dim mese As String = colroot.Get("mese")
        Dim giorno As String = colroot.Get("giorno")
        Dim kwh As String = colroot.Get("kwh")
        Dim NumRiga As Int=0
        Dim row As Int
        Dim Riga As String
        Riga=anno&","&mese&","&giorno&","&kwh
        Dim components() As String
'        Log(components)
        components = Regex.Split(",", Riga) 'returns: "abc", "def", "", "ghi"
        For i = 0 To components.Length-1
            If row Mod 2 = 0 Then
                sb.Append("<tr>")
            Else
                sb.Append("<tr class='odd'>")
            End If
            For i = 0 To components.Length -1
                sb.Append("<td>")
                sb.Append(components(i))
                sb.Append("</td>")
            Next
            sb.Append("</tr>").Append(CRLF)
            row = row + 1
        Next
    Next
    sb.Append("</table></body></html>")
    WebView1.Enabled=True
    WebView1.Visible=True
    WebView1.LoadHtml(sb.ToString)
End Sub

Sub PrendiKwhProdotti(tipologia As String) As List
    If tipologia="ASC" Then
        tipologia="999999"
    Else
        tipologia="888888"
    End If
'    PublicData.Initialize
    Dim Risposta As String = asJava(Me).RunMethod("GetJson",Array(url,tipologia))
    Dim parser As JSONParser
    parser.Initialize(Risposta)
    Return parser.NextArray
End Sub
 
Upvote 0

Angelo Messina

Active Member
Licensed User
Longtime User
B4X:
Sub CreaWeb(Tipo As String)

    IndiceGenerale = asJava(Me).RunMethod("GetData",Array(url,"ID","-1"))
    Private HtmlCSS As String = $"
        table {width: 100%;border: 1px solid #cef;text-align: left; }
        th { font-weight: bold;    background-color: #acf;    border-bottom: 1px solid #cef; }
        td,th {    padding: 4px 5px; }
        .odd {background-color: #def; }
        .odd td {border-bottom: 1px solid #cef; }
        a { text-decoration:none; color: #000;}"$       
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append("<html><body>").Append(CRLF)
    sb.Append("<style type='text/css'>").Append(HtmlCSS).Append("</style>").Append(CRLF)
    sb.Append("<table><thead><tr>").Append(CRLF)
    sb.Append("<th>").Append("Anno").Append("</th>")
    sb.Append("<th>").Append("Mese").Append("</th>")
    sb.Append("<th>").Append("Giorno").Append("</th>")
    sb.Append("<th>").Append("Kwh").Append("</th>")
    sb.Append("</thead>")
    sb.Append("</tr>").Append(CRLF)
    Dim row As Int
    For Each colroot As Map In PrendiKwhProdotti(Tipo)
        Dim anno As String = colroot.Get("anno")
        Dim mese As String = colroot.Get("mese")
        Dim giorno As String = colroot.Get("giorno")
        Dim kwh As String = colroot.Get("kwh")
        Dim NumRiga As Int=0
        Dim row As Int
        Dim Riga As String
        Riga=anno&","&mese&","&giorno&","&kwh
        Dim components() As String
'        Log(components)
        components = Regex.Split(",", Riga) 'returns: "abc", "def", "", "ghi"
        For i = 0 To components.Length-1
            If row Mod 2 = 0 Then
                sb.Append("<tr>")
            Else
                sb.Append("<tr class='odd'>")
            End If
            For i = 0 To components.Length -1
                sb.Append("<td>")
                sb.Append(components(i))
                sb.Append("</td>")
            Next
            sb.Append("</tr>").Append(CRLF)
            row = row + 1
        Next
    Next
    sb.Append("</table></body></html>")
    WebView1.Enabled=True
    WebView1.Visible=True
    WebView1.LoadHtml(sb.ToString)
End Sub

Sub PrendiKwhProdotti(tipologia As String) As List
    If tipologia="ASC" Then
        tipologia="999999"
    Else
        tipologia="888888"
    End If
'    PublicData.Initialize
    Dim Risposta As String = asJava(Me).RunMethod("GetJson",Array(url,tipologia))
    Dim parser As JSONParser
    parser.Initialize(Risposta)
    Return parser.NextArray
End Sub
Java:
public static String GetJson(String baseUrl,String Tipo) throws IOException {
    // Creazione della connessione al server
    String serverUrl = baseUrl+"?ID="+Tipo;   //" 999999";
    System.out.println("Query " + serverUrl);
    URL url = new URL(serverUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");

    // Lettura della risposta dal server
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    // Visualizzazione della risposta come stringa JSON
    System.out.println("Risposta JSON: " + response.toString());
    // Chiusura della connessione
    connection.disconnect();
    return response.toString();
}
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Caused by: android.os.NetworkOnMainThreadException

Are you running any network task on the main thread instead of in a background task?
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Sorry, I don't do Android, I just googled android.os.NetworkOnMainThreadException and there were several suggestions to prevent this error, but not sure how you would implement in B4A.
 
Upvote 0
Top