Android Question Use OkHttpUtils2 inside a function

Vahid2016

Member
Licensed User
I got the following piece of code from https://www.b4x.com/android/forum/threads/b4x-okhttputils2-with-wait-for.79345/#content

B4X: Copy
Dim j As HttpJob
j.Initialize("", Me)
j.Download("https://www.google.com")
Wait For (j) JobDone(j As HttpJob)
If j.Success Then
   Log(j.GetString)
End If
j.Release

It works fine.
Now I have a Code Module named functions. I want to add a function like the following:

B4X: Copy
Sub GetLatestNews(activity As Object) As Boolean 'ignore
     
    Dim job As HttpJob
    job.Initialize("",activity)
        job.Download("http://MyUrl/api/news")
    Wait For (job) JobDone(job As HttpJob)
    If job.Success Then
         
            'Some Code here
      
    End If
    job.Release
     
End Sub

But B4A IDE says "Static Code Modules can't handle events"
 
Now I have a Code Module named functions
You can not use Sleep or Wait For or use any Events in a Code Module.

Use the Code in a Activity, a Service, or better make the module a Class as already suggested by @agraham
 
Upvote 0
I tried using Standard Class Module instead of Code Module:
B4X: Copy
Sub Class_Globals

    Dim JustALabel As Label  'Ignore Just 4 getting rid of the error : Activity context is required
 
End Sub

Public Sub Initialize
 
End Sub


Sub GetLatestNews() As String 'ignore
  
    Dim job As HttpJob
    job.Initialize("",Me)
    job.Download("MyUrl/api/news")
    Wait For (job) JobDone(job As HttpJob)
    If job.Success Then
     
     
        Dim res As String
        res = job.GetString
     
        job.Release
        Return res
    Else
     
        job.Release
        Return "Error Here"

    End If
 
  
End Sub

Now I got a new error . "ResumableSub return type must be resumablesub or none"
But I need my method returns what happened and what caused the error
 
Upvote 0
Read this
In the class
B4X: Copy
Sub GetLatestNews As ResumableSub
    ...
    Return Res
End Sub
Elsewhere
B4X: Copy
Dim MyClass1 as MyClass
MyClass1.Initialize
...
Wait For (MyClass1.GetlatestNews) Complete (result as String)
...
End Sub
I think I got the syntax correct!
 
Upvote 0
Thank you agraham , How can I return the reason behind the failure?
Do you think I should return string or boolean?
Do I need to to use try catch inside the method to get the reason?
 
Upvote 0
There are several options open to you.

1) If you only want to return success or failure return a Boolean.

2) If want to return some data on success you could return a Boolean and place the data in a global String variable, or return the data in a String and use a special value to indicate failure. e.g. "<*Failure reason*>".

3) Also you could return a String array with one element as a success indicator and other elements containing other data.
 
Upvote 0
Back
Top