Search code examples
google-fit

Insert TYPE_NUTRITION in Google Fit


I get user input (calorie) and want to insert it in Google Fit but the insertion does not work.

private DataSet insertNutritionData(){
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    long endTime = cal.getTimeInMillis();

    DataSource nutritionSource = new DataSource.Builder()
            .setAppPackageName(getApplicationContext().getPackageName())
            .setDataType(DataType.TYPE_NUTRITION)
            .setType(DataSource.TYPE_RAW)
            .build();

    DataSet dataSet = DataSet.create(nutritionSource);

    DataPoint dataPoint = DataPoint.create(nutritionSource);
    dataPoint.setTimestamp(endTime, TimeUnit.MILLISECONDS); 
    dataPoint.getValue(Field.FIELD_NUTRIENTS).setKeyValue(Field.NUTRIENT_CALORIES,calorie);                          

    dataSet.add(dataPoint);

    return dataSet;

}

The insertion is done in AsyncTask :

private class InsertAndVerifyNutritionTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {

        DataSet dataSet = insertNutritionData();

        Log.i(TAG, "Inserting the dataset in the History API");
        com.google.android.gms.common.api.Status insertStatus =
                Fitness.HistoryApi.insertData(mClient, dataSet)
                        .await(1, TimeUnit.MINUTES);

        if (!insertStatus.isSuccess()) {
            Log.i(TAG, "There was a problem inserting the dataset.");

            return null;
        }

        Log.i(TAG, "Data insert was successful!");            

        return null;
    }
}

Unfortunately, the insertion is not done and I don't know why. There is no sample to explain how can we use TYPE_NUTRIENTS...

Thanks a lot !

[UPDATE]

I found this error :

Couldn't connect to Google API client: ConnectionResult{statusCode=API_UNAVAILABLE, resolution=null}

However, I build my client like this :

mClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.RECORDING_API)
            .addApi(Fitness.SENSORS_API)
            .addApi(Fitness.HISTORY_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addScope(new Scope(Scopes.FITNESS_NUTRITION_READ_WRITE))
            .addConnectionCallbacks(
                    new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {
                            Log.i(TAG, "Google Fit connected.");
                            mTryingToConnect = false;
                            Log.d(TAG, "Notifying the UI that we're connected.");
                            notifyUiFitConnected();

                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                            // If your connection to the sensor gets lost at some point,
                            // you'll be able to determine the reason and react to it here.
                            mTryingToConnect = false;
                            if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
                                Log.i(TAG, "Connection lost.  Cause: Network Lost.");
                            } else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
                                Log.i(TAG, "Connection lost.  Reason: Service Disconnected");
                            }
                        }
                    }
            )
            .addOnConnectionFailedListener(
                    new GoogleApiClient.OnConnectionFailedListener() {
                        // Called whenever the API client fails to connect.
                        @Override
                        public void onConnectionFailed(ConnectionResult result) {
                            //Toast.makeText(getActivity(),"connection failed 1",Toast.LENGTH_SHORT).show();
                            mTryingToConnect = false;
                            notifyUiFailedConnection(result);
                        }
                    }
            )
            .build();
}

Moreover, I don't understand why I cannot connect to fit whereas it worked perfectly...

Updated with the manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.webear.mysilhouette">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
    android:allowBackup="true"
    android:label="mySilhouette"
    android:icon="@drawable/ic_launcher"
    >

    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

<service
    android:enabled="true"
    android:name="com.example.webear.mysilhouette.GoogleApiIntentService"/>

(...)

</application>

</manifest>

Kamel


Solution

  • The statusCode says API_UNAVAILABLE. It means:

    One of the API components you attempted to connect to is not available. The API will not work on this device, and updating Google Play services will not likely solve the problem. Using the API on the device should be avoided.

    Maybe try another device? Or Play Services are misconfigured.