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

694 views Asked by At

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

2

There are 2 answers

1
Semanticer On BEST ANSWER

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);
0
Juangui Jordán On

Reading some bananas:

    // Somewhere in your class definitions
    private static final String TAG = "NutritionHistory";
    private static final String[] NUTRIENTS_ARRAY = new String[] {
            Field.NUTRIENT_CALORIES,
            Field.NUTRIENT_TOTAL_FAT,
            Field.NUTRIENT_SATURATED_FAT,
            Field.NUTRIENT_UNSATURATED_FAT,
            Field.NUTRIENT_POLYUNSATURATED_FAT,
            Field.NUTRIENT_MONOUNSATURATED_FAT,
            Field.NUTRIENT_TRANS_FAT,
            Field.NUTRIENT_CHOLESTEROL,
            Field.NUTRIENT_SODIUM,
            Field.NUTRIENT_POTASSIUM,
            Field.NUTRIENT_TOTAL_CARBS,
            Field.NUTRIENT_DIETARY_FIBER,
            Field.NUTRIENT_SUGAR,
            Field.NUTRIENT_PROTEIN,
            Field.NUTRIENT_VITAMIN_A,
            Field.NUTRIENT_VITAMIN_C,
            Field.NUTRIENT_CALCIUM,
            Field.NUTRIENT_IRON
    };

    // Then for reading data
    public someMethodForReading(long startTime, long endTime) {

        DataReadRequest readRequest = new DataReadRequest.Builder()
                .aggregate(DataType.TYPE_NUTRITION, DataType.AGGREGATE_NUTRITION_SUMMARY)
                .bucketByTime(1, TimeUnit.DAYS)
                .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS).build();

        DataReadResult dataReadResult = Fitness.HistoryApi.readData(googleFitManager.getGoogleApiClient(), readRequest)
                .await(1, TimeUnit.MINUTES);

        for (Bucket bucket : dataReadResult.getBuckets()) {
            List<DataSet> dataSets = bucket.getDataSets();
            for (DataSet dataSet : dataSets) {

                // Getting individual datapoints (one for each date)
                for (DataPoint dp : dataSet.getDataPoints()) {
                    Date date = new Date(dp.getStartTime(TimeUnit.MILLISECONDS));
                    String foodItem = dp.getValue(FIELD_FOOD_ITEM).asString();
                    int mealType = dp.getValue(FIELD_MEAL_TYPE).asInt();

                    Value nutrients = dp.getValue((Field.FIELD_NUTRIENTS));

                    HashMap<String, Float> nutrients = getNutrientsAsMap(nutrients);
                    // Do something with your data
                    // ...
                }
            }
        }

    }

    // The method where the 'magic' happens
    private HashMap<String, Float> getNutrientsAsMap(Value nutrients) {
        HashMap<String, Float> nutrientsMap = new HashMap<>();

        for (String nutrientKey : NUTRIENTS_SET) {
            try {
                Float nutrientVal = nutrients.getKeyValue(nutrientKey);
                nutrientsMap.put(nutrientKey, nutrientVal);
            } catch (Exception e) {
            }
        }

        return nutrientsMap;
    }