Android Question How can I put the example of downloading a quote in a service?

asales

Expert
Licensed User
Longtime User
In this post I saw a code to download a quote:
https://www.b4x.com/android/forum/threads/b4x-okhttputils2-with-wait-for.79345/
B4X:
Sub DownloadQuote
   Dim j As HttpJob
   j.Initialize("", Me) 
   j.Download("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand")
   Wait For (j) JobDone(j As HttpJob)
   If j.Success Then
     Dim jp As JSONParser
     jp.Initialize(j.GetString)
     Dim quotes As List = jp.NextArray
     For Each quot As Map In quotes
       LabelQuote.Text = quot.Get("title") & CRLF & quot.Get("content")
     Next
   End If
   j.Release
End Sub
I have a similar code to download a text and show the text in a label in the main activity.

How I can put this code in a service, call it and show the quote received in a label (LabelQuote) in main activity?

Thanks in advance for any tip.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Add this sub in the activity:
B4X:
Public Sub SetLabelQuote(Quotes As List)
 'this should be considered bad code. See the strings video tutorial and switch to StringBuilder.
For Each quot As Map In quotes
       LabelQuote.Text = quot.Get("title") & CRLF & quot.Get("content")
     Next
End Sub

B4X:
'Starter service
Sub DownloadQuote
   Dim j As HttpJob
   j.Initialize("", Me) 
   j.Download("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand")
   Wait For (j) JobDone(j As HttpJob)
   If j.Success Then
     Dim jp As JSONParser
     jp.Initialize(j.GetString)
     Dim quotes As List = jp.NextArray
     CallSub2(Main, "SetLabelQuote", quotes)
   End If
   j.Release
End Sub

The CallSub will be ignored if the main activity is paused. You can also store the quotes in a process global variable and use it in Activity_Resume of the Main activity to set the quotes.
 
Upvote 0

asales

Expert
Licensed User
Longtime User
The CallSub will be ignored if the main activity is paused. You can also store the quotes in a process global variable and use it in Activity_Resume of the Main activity to set the quotes.
Thanks!
I tried another change in the code and put the DownloadQuote in a service (ServiceJobs) with a parameter label.
B4X:
Sub DownloadQuote(lbQuote As Label)
...
    For Each colroot As Map In root
        lbQuote.Text = colroot.Get("text")
    Next
...
I call it from activity Main and passes the label in the parameter:
B4X:
CallSubDelayed2(ServiceJobs,"DownloadQuote",lbQuote)
Is a good pratice too?
 
Upvote 0
Top