Search code examples
androidgoogle-fit

How to add nutrion information about consumed food to google fit history on android?


I want to let users of my app add info about food they eat and I need to save nutrition info to google fit history. I'm connected to google play services and I hope I request correct API and Scope.

mClient = new GoogleApiClient.Builder(this)
                .addApi(Fitness.HISTORY_API)
                .addScope(new Scope(Scopes.FITNESS_NUTRITION_READ_WRITE))
                ...

But can't find any good examples how to add data with all the nurtition info to users google fit history. I think I need to use com.google.nutrition DATA_TYPE and fill all the fields somehow, but there is no code snippet to show me exactly how to do that.

Thanks for any help


Solution

  • It turns out there is something in google fit doc after all. Create your banana:

     DataSource nutritionSource = new DataSource.Builder()
         .setDataType(TYPE_NUTRITION)
         ...
         .build();
    
     DataPoint banana = DataPoint.create(nutritionSource);
     banana.setTimestamp(now.getMillis(), MILLISECONDS);
     banana.getValue(FIELD_FOOD_ITEM).setString("banana");
     banana.getValue(FIELD_MEAL_TYPE).setInt(MEAL_TYPE_SNACK);
     banana.getValue(FIELD_NUTRIENTS).setKeyValue(NUTRIENT_TOTAL_FAT, 0.4f);
     banana.getValue(FIELD_NUTRIENTS).setKeyValue(NUTRIENT_SODIUM, 1f);
     banana.getValue(FIELD_NUTRIENTS).setKeyValue(NUTRIENT_POTASSIUM, 422f);
    

    Then you probably want to save your banana:

    DataSet dataSet = DataSet.create(nutritionSource);
    dataSet.add(banana);
    PendingResult<Status> result = Fitness.HistoryApi.insertData(mClient, dataSet);