Android Tutorial [B4X] Working with GoogleTasks using REST

DonManfred

Expert
Licensed User
GoogleTasks are a Task list (ToDo List, Shopping List, whateveryouwant list)

In this small Tutorial i want to share my findings while i played around with GoogleTasks. In fact i´m not finished playing with it ;-)

Based on @Erel answer that it most probably work in B4J and B4i too i added [B4X] to the Threadtitle.

Dependencies:
- Setup OAuth2 in your Project. [Class][B4X]Google OAuth2
- Be familar with okhttputils2.

Initialize the Authclass using the following Scope
B4X:
    oauth2.Initialize(Me, "oauth2", ClientId, "https://www.googleapis.com/auth/tasks", ClientSecret, File.DirData("GoogleTasks"))
- the baseUrl used is always
B4X:
Private BaseURL As String = "https://www.googleapis.com/tasks/v1"
The custom Types used here are (you should add them to Process globals
B4X:
    Type Tasklist (kind As String, id As String, title As String, updated As String, selfLink As String)
    Type Task (kind As String, id As String, etag As String, title As String, updated As String, selflink As String, position As String, notes As String, status As String, due As String)

To get a List of all Tasklists the authenticated User has Access to:
B4X:
Sub btnGetData_Action
    oauth2.GetAccessToken
    Wait For OAuth2_AccessTokenAvailable (Success As Boolean, Token As String)
    If Success = False Then
        Log("Error accessing account.")
        Return
    End If
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download2($"${BaseURL}/users/@me/lists"$, _
         Array As String("access_token", Token))
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        'Log(j.GetString)
        ParseNotelistsData(j.GetString)
    Else
        oauth2.ResetToken
        Log("Online data not available.")
    End If
    j.Release
End Sub
Sub ParseNotelistsData (data As String)
    clvNotelist.Clear
    Dim jp As JSONParser
    jp.Initialize(data)
    Dim root As Map = jp.NextObject
    Dim kind As String = root.Get("kind")
    Dim etag As String = root.Get("etag")
    Dim items As List = root.Get("items")
    For Each colitems As Map In items
 
        Dim item As Map = colitems
        Dim kind As String = colitems.Get("kind")
        Dim id As String = colitems.Get("id")
        Dim title As String = colitems.Get("title")
        Dim updated As String = colitems.Get("updated")
        Dim selfLink As String = colitems.Get("selfLink")
        Dim list As Tasklist
        list.Initialize
        list.kind = kind
        list.id = id
        list.selfLink = selfLink
        list.title = title
        list.updated = updated
        clvNotelist.AddTextItem(title,list)
    Next
    Log(root)
End Sub

To get a List of all Tasks in a Tasklist with the given tasklistID:
B4X:
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download2($"https://www.googleapis.com/tasks/v1/lists/${tasklistID}/tasks"$, _
         Array As String("access_token", Token))
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
        Dim parser As JSONParser
        parser.Initialize(j.GetString)
        Dim root As Map = parser.NextObject
        'Dim kind As String = root.Get("kind")
        'Dim etag As String = root.Get("etag")
        Dim items As List = root.Get("items")
        If items <> Null And items.IsInitialized Then
            For Each colitems As Map In items
                Dim item As Map = colitems
                Dim task As Task
                task.Initialize
                task.due = item.Get("due")
                task.etag = item.Get("etag")
                task.kind = item.Get("kind")
                task.id = item.Get("id")
                task.position = item.Get("position")
                task.title = item.Get("title")
                task.updated = item.Get("updated")
                task.selflink = item.Get("selfLink")
                task.status = item.Get("status")
                clvNotes.AddTextItem(task.Title,task)
            Next
        End If
    Else
        Log("Online data not available.")
    End If
    j.Release
To delete a given Tasklist tasklistID:
B4X:
    Dim j As HttpJob
    j.Initialize("", Me)
    ' Delete the given Tasklist from the Authenticated User
    j.Delete2($"${BaseURL}/users/@me/lists/${tasklistID}"$, _
         Array As String("access_token", AccessToken))
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
    Else
        'oauth2.ResetToken
        Log(j.ErrorMessage)
        Log("Online data not available.")
    End If
    j.Release

To create a new Tasklist:
B4X:
    Dim listName As String = edtTasklistName.Text.Trim
 
    Dim taskinfo As Map
    taskinfo.Initialize
    taskinfo.Put("title": listName)
 
    Dim jgen As JSONGenerator
    jgen.Initialize(taskinfo)
 
    Dim j As HttpJob
    j.Initialize("", Me)
    ' Insert a new Tasklist with the title set to listName
    j.PostString($"${BaseURL}/users/@me/lists/?access_token=${AccessToken}"$, jgen.ToString)
    j.GetRequest.SetContentType("application/json")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
        btnGetData_Action
    Else
        'oauth2.ResetToken
        Log(j.ErrorMessage)
        Log("Online data not available.")
    End If
    j.Release
Create a new Task in a given Tasklist:

B4X:
    Dim title As String = edtTaskTitle.Text.Trim
    Dim notes As String =  memoNotes.Text.Trim
    
    Dim taskinfo As Map
    taskinfo.Initialize
    taskinfo.Put("title": title)
    taskinfo.Put("notes": notes)
    
    If edtDueDate.Text.Trim = "" Then
    
        Dim duedate As Long = DateTime.DateTimeParse("12/31/2018","12:31:00")
        taskinfo.Put("due": CreatenewTaskDatetime(duedate))
    Else
        taskinfo.Put("due": edtDueDate.Text.Trim)
    End If

    Dim jgen As JSONGenerator
    jgen.Initialize(taskinfo)
    
    Dim j As HttpJob
    j.Initialize("", Me)
    ' Insert a new Tasklist with the title set to listName
    j.PostString($"${BaseURL}/lists/${lblTalklistID.Text}/tasks/?access_token=${AccessToken}"$, jgen.ToString)
    j.GetRequest.SetContentType("application/json")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
        btnGetData_Action
    Else
        'oauth2.ResetToken
        Log(j.ErrorMessage)
        Log("Online data not available.")
    End If
    j.Release
Code needed
B4X:
Sub CreatenewTaskDatetime(taskdue As Long) As String
    Dim olddateformat As String = DateTime.DateFormat
    DateTime.DateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    Dim result As String = DateTime.Date(taskdue)
    DateTime.DateFormat = olddateformat   
    Return result
End Sub
I´ll add more Examples if there is interest for it (i see it on the Likes received :)).

Please create a new Thread for any Questions or Issues you have.
 
Last edited:

DonManfred

Expert
Licensed User
that it will most probably work as-is with B4J and B4i
I´m sure about B4J as i´m doing my tests with B4J (much faster Compile and starting times). I was not sure about B4i and that´s the reason i did not added [b4x] to the title. I´ll add it.
 
Last edited:

DonManfred

Expert
Licensed User
Update a specific Task in a Talklist using Patch semantics:

B4X:
    Dim taskinfo As Map
    taskinfo.Initialize
    taskinfo.Put("title": "New Title") ' Define all Properties you want to update. Only the ones who needs to get changed must be listed.

    Dim jgen As JSONGenerator
    jgen.Initialize(taskinfo)

    Dim j As HttpJob
    j.Initialize("", Me)
    ' Patch a specific Taskitem
    j.PatchString($"${BaseURL}/lists/${task.tasklistID}/tasks/${task.id}?access_token=${AccessToken}"$, jgen.ToString)
    j.GetRequest.SetContentType("application/json")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
        btnGetData_Action
    Else
        'oauth2.ResetToken
        Log(j.ErrorMessage)
        Log("Online data not available.")
    End If
    j.Release
 
Last edited:

DonManfred

Expert
Licensed User
Two ways of Authentication (in URL or in a Header):

The Authentication can be done in 2 ways:
1. Adding ?access_token=yourtoken to the URL like in the Examples above. access_token is the keyname.
2. You can set a Header instead. As example i do another Patch on a specific Task like in Post #4.
B4X:
    Dim taskinfo As Map
    taskinfo.Initialize
    taskinfo.Put("title": "Another new Title")

    Dim jgen As JSONGenerator
    jgen.Initialize(taskinfo)

    Dim j As HttpJob
    j.Initialize("", Me)
    ' Patch a specific Taskitem
    j.PatchString($"${BaseURL}/lists/${task.tasklistID}/tasks/${task.id}"$, jgen.ToString) ' Note that there is no token in the url anymore.
    j.GetRequest.SetHeader("Authorization","Bearer "&AccessToken) ' The token is now used in a Authorization Header with Value set to "Bearer yourtoken"
    j.GetRequest.SetContentType("application/json")
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
        btnGetData_Action
    Else
        'oauth2.ResetToken
        Log(j.ErrorMessage)
        Log("Online data not available.")
    End If
    j.Release
 
Top