Android Tutorial FitBit Authentification and use of the FitBit Web Api (http)

Fitbit_app_icon.png FitBit OAuth and HTTP SDK

You need to define an App in the FitBit Console at https://dev.fitbit.com/apps

Make sure to set your "OAuth 2.0 Application Type" to Client

You need the "OAuth 2.0 Client ID". It is a short (6 Chars) Alphanumeric Value. Copy it as you need it in the Examplecode...

B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
    access_token = ""
    client_id = "your client id here"

Basically it is using a Webview to show the Request to the User:
B4X:
Sub Button1_Click
    www.LoadUrl("https://www.fitbit.com/oauth2/authorize?response_type=token&client_id="&client_id&"&redirect_uri=http%3A%2F%2Fdonmanfred.basic4android.de%2F&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight")
End Sub
Make sure to update the redirect_uri to match your Server

In page_finished Event of the Webview we chevk for the existence of a token and Extract it

B4X:
Sub www_PageFinished (Url As String)
    Log($"www_PageFinished(${Url})"$)
    If Url.Contains("#access_token") Then
        Dim token As String = Url.SubString(Url.IndexOf("#access_token")+14)
        Log(token)
        access_token = token.SubString2(0,token.IndexOf("&"))
        Log("Access Token = "&access_token)
    End If
End Sub
You should store the token to a Database, KVS or whatever to restore it when you restart the app.

After you successfully got a token you can use it to use the http sdk from FitBit

Get the active User Profile:
B4X:
Sub Button2_Click
    Dim job As HttpJob
    job.Initialize("Profile",Me)
    job.Download("https://api.fitbit.com/1/user/-/profile.json")
    job.GetRequest.SetHeader("Authorization","Bearer "&access_token)
    wait for (job) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
        'Dim OutStream As OutputStream = File.OpenOutput(File.DirRootExternal, "Result.txt", False)
        'File.Copy2(job.GetInputStream,OutStream) ' save the file
        'OutStream.Close
 
        Dim parser As JSONParser
        parser.Initialize(j.GetString)
        Dim root As Map = parser.NextObject
        Dim user As Map = root.Get("user")
        Dim distanceUnit As String = user.Get("distanceUnit")
        Dim gender As String = user.Get("gender")
        Dim displayName As String = user.Get("displayName")
        Dim timezone As String = user.Get("timezone")
        Dim waterUnit As String = user.Get("waterUnit")
        Dim isGraduationAvailable As String = user.Get("isGraduationAvailable")
        Dim avatar640 As String = user.Get("avatar640")
        Dim clockTimeDisplayFormat As String = user.Get("clockTimeDisplayFormat")
        Dim displayNameSetting As String = user.Get("displayNameSetting")
        Dim locale As String = user.Get("locale")
        Dim offsetFromUTCMillis As Int = user.Get("offsetFromUTCMillis")
        Dim foodsLocale As String = user.Get("foodsLocale")
        Dim strideLengthRunningType As String = user.Get("strideLengthRunningType")
        Dim autoStrideEnabled As String = user.Get("autoStrideEnabled")
        Dim features As Map = user.Get("features")
        Dim exerciseGoal As String = features.Get("exerciseGoal")
        Dim memberSince As String = user.Get("memberSince")
        Dim waterUnitName As String = user.Get("waterUnitName")
        Dim mfaEnabled As String = user.Get("mfaEnabled")
        Dim heightUnit As String = user.Get("heightUnit")
        Dim isChild As String = user.Get("isChild")
        Dim height As Int = user.Get("height")
        Dim strideLengthWalking As Double = user.Get("strideLengthWalking")
        Dim avatar150 As String = user.Get("avatar150")
        Dim topBadges As List = user.Get("topBadges")
        For Each coltopBadges As Map In topBadges
            Dim dt As String = coltopBadges.Get("dateTime")
            Dim timesAchieved As Int = coltopBadges.Get("timesAchieved")
            Dim badgeGradientStartColor As String = coltopBadges.Get("badgeGradientStartColor")
            Dim image100px As String = coltopBadges.Get("image100px")
            Dim image50px As String = coltopBadges.Get("image50px")
            Dim shareImage640px As String = coltopBadges.Get("shareImage640px")
            Dim description As String = coltopBadges.Get("description")
            Dim shortDescription As String = coltopBadges.Get("shortDescription")
            Dim badgeGradientEndColor As String = coltopBadges.Get("badgeGradientEndColor")
            Dim encodedId As String = coltopBadges.Get("encodedId")
            Dim earnedMessage As String = coltopBadges.Get("earnedMessage")
            Dim badgeType As String = coltopBadges.Get("badgeType")
            Dim image300px As String = coltopBadges.Get("image300px")
            Dim marketingDescription As String = coltopBadges.Get("marketingDescription")
            Dim name As String = coltopBadges.Get("name")
            Dim shareText As String = coltopBadges.Get("shareText")
            Dim image125px As String = coltopBadges.Get("image125px")
            Dim image75px As String = coltopBadges.Get("image75px")
            Dim category As String = coltopBadges.Get("category")
            Dim shortName As String = coltopBadges.Get("shortName")
            Dim value As Int = coltopBadges.Get("value")
            Dim cheers As List = coltopBadges.Get("cheers")
            Dim mobileDescription As String = coltopBadges.Get("mobileDescription")
        Next
        Dim familyGuidanceEnabled As String = user.Get("familyGuidanceEnabled")
        Dim strideLengthRunning As Double = user.Get("strideLengthRunning")
        Dim fullName As String = user.Get("fullName")
        Dim weight As Int = user.Get("weight")
        Dim dateOfBirth As String = user.Get("dateOfBirth")
        Dim avatar As String = user.Get("avatar")
        Dim encodedId As String = user.Get("encodedId")
        Dim swimUnit As String = user.Get("swimUnit")
        Dim startDayOfWeek As String = user.Get("startDayOfWeek")
        Dim glucoseUnit As String = user.Get("glucoseUnit")
        Dim corporate As String = user.Get("corporate")
        Dim ambassador As String = user.Get("ambassador")
        Dim strideLengthWalkingType As String = user.Get("strideLengthWalkingType")
        Dim corporateAdmin As String = user.Get("corporateAdmin")
        Dim averageDailySteps As Int = user.Get("averageDailySteps")
        Dim age As Int = user.Get("age")
        Dim weightUnit As String = user.Get("weightUnit")
        Log($"Age ${age} - Steps Average = ${averageDailySteps}"$)
    Else
        Log("JobError: "&job.ErrorMessage)
    End If
End Sub

Get the active User Activities:
B4X:
Sub Button3_Click
    Dim job As HttpJob
    job.Initialize("activities",Me)
    job.Download("https://api.fitbit.com/1/user/-/activities.json")
    job.GetRequest.SetHeader("Authorization","Bearer "&access_token)
    wait for (job) JobDone(j As HttpJob)
    If j.Success Then
        Log(j.GetString)
        'Dim OutStream As OutputStream = File.OpenOutput(File.DirRootExternal, "Result2.txt", False)
        'File.Copy2(job.GetInputStream,OutStream) ' save the file
        'OutStream.Close
 
        Dim parser As JSONParser
        parser.Initialize(j.GetString)
        Dim root As Map = parser.NextObject
        Dim lifetime As Map = root.Get("lifetime")
        Dim total As Map = lifetime.Get("total")
        Dim floors As Int = total.Get("floors")
        Dim distance As Double = total.Get("distance")
        Dim caloriesOut As Int = total.Get("caloriesOut")
        Dim activeScore As Int = total.Get("activeScore")
        Dim steps As Int = total.Get("steps")
        Dim tracker As Map = lifetime.Get("tracker")
        Dim floors As Int = tracker.Get("floors")
        Dim distance As Double = tracker.Get("distance")
        Dim caloriesOut As Int = tracker.Get("caloriesOut")
        Dim activeScore As Int = tracker.Get("activeScore")
        Dim steps As Int = tracker.Get("steps")
        Dim best As Map = root.Get("best")
        Dim total As Map = best.Get("total")
        Dim floors As Map = total.Get("floors")
        Dim date As String = floors.Get("date")
        Dim value As Double = floors.Get("value")
        Dim distance As Map = total.Get("distance")
        Dim date As String = distance.Get("date")
        Dim value As Double = distance.Get("value")
        Dim steps As Map = total.Get("steps")
        Dim date As String = steps.Get("date")
        Dim value As Int = steps.Get("value")
        Dim tracker As Map = best.Get("tracker")
        Dim floors As Map = tracker.Get("floors")
        Dim date As String = floors.Get("date")
        Dim value As Double = floors.Get("value")
        Dim distance As Map = tracker.Get("distance")
        Dim date As String = distance.Get("date")
        Dim value As Double = distance.Get("value")
        Dim steps As Map = tracker.Get("steps")
        Dim date As String = steps.Get("date")
        Dim value As Int = steps.Get("value")
        'Log($"Age ${age} - Steps Average = ${averageDailySteps}"$)
    Else
        Log("JobError: "&job.ErrorMessage)
    End If
 
End Sub
 

Attachments

  • FitBitEx.zip
    11 KB · Views: 390
Last edited:

pas

Member
Licensed User
Longtime User
Hello @DonManfred - I am trying to understand this example and was hoping you could explain how the redirect_uri works. If I understand correctly, this is an external web server that you set up. Can you please elaborate on what is running on that server and how it interacts with this sample? I am trying to do something similar but I am stuck on this part. With the Google OAuth2 library it supports a "fake" URI which is set to the package name. But the OAuth server I am working with (and I suspect the FitBit server too) requires a valid URL.

Any help is appreciated.
-Paul
 

DonManfred

Expert
Licensed User
Longtime User
and I suspect the FitBit server too) requires a valid URL
1. You should never post to existing threads. Always create a new thread in the qustionsforum for any Issue you have.
2. Google is working. You can use it to find out what the redirecturi is. In this case the url is one of my domains. You can use the redirecturi to get infos about this authentification on serverside.
 
Top