Search code examples
androidgoogle-fitgoogle-fit-sdkhydration

Cannot insert hydration data to Google Fit


I am trying to insert a hydration data into the Google Fit. But I unable to insert the data.

Here is my code:

BuildFitnessClient:

private void buildFitnessClient() {
    Log.w("Fit","inside buildFitness");
    // Create the Google API Client
    if (mClient == null) {
        mClient = new GoogleApiClient.Builder(this)
                .addApi(Fitness.HISTORY_API)
                .addApi(Fitness.SESSIONS_API)
                //.addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
                .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
                .addConnectionCallbacks(
                        new GoogleApiClient.ConnectionCallbacks() {
                            @Override
                            public void onConnected(Bundle bundle) {
                                Log.i(TAG, "Connected!!!");
                                // Now you can make calls to the Fitness APIs.  What to do?
                                // Play with some sessions!!
                                new InsertAndVerifyDataTask().execute();
                            }

                            @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.
                                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");
                                }
                            }
                        }
                )
                .enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(ConnectionResult result) {
                        Log.i(TAG, "Google Play services connection failed. Cause: " +
                                result.toString());
                        Snackbar.make(
                                DeviceControlActivity.this.findViewById(R.id.gatt_services),
                                "Exception while connecting to Google Play services: " +
                                        result.getErrorMessage(),
                                Snackbar.LENGTH_INDEFINITE).show();
                    }
                })
                .build();
    }
}

InsertandVerifyData:

private class InsertAndVerifyDataTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {
        // Create a new dataset and insertion request.
        DataSet dataSet = insertFitnessData();

        // [START insert_dataset]
        // Then, invoke the History API to insert the data and await the result, which is
        // possible here because of the {@link AsyncTask}. Always include a timeout when calling
        // await() to prevent hanging that can occur from the service being shutdown because
        // of low memory or other conditions.
        Log.i(TAG, "Inserting the dataset in the History API.");
        Log.w("Fit", "Inserting the dataset in the HISTORY api");
        com.google.android.gms.common.api.Status insertStatus =
                Fitness.HistoryApi.insertData(mClient, dataSet)
                        .await(1, TimeUnit.MINUTES);

        // Before querying the data, check to see if the insertion succeeded.
        if (!insertStatus.isSuccess()) {
            Log.i(TAG, "There was a problem inserting the dataset.");
            Log.w("Fit", "Error inserting data");
            return null;
        }

        // At this point, the data has been inserted and can be read.
        Log.i(TAG, "Data insert was successful!");
        // [END insert_dataset]

        // Begin by creating the query.
      // DataReadRequest readRequest = queryFitnessData();

        // [START read_dataset]
        // Invoke the History API to fetch the data with the query and await the result of
        // the read request.
       // DataReadResult dataReadResult =
         //       Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);
        // [END read_dataset]

        // For the sake of the sample, we'll print the data so we can see what we just added.
        // In general, logging fitness information should be avoided for privacy reasons.

      //  printData(dataReadResult);

        return null;
    }
}

InsertData:

private DataSet insertFitnessData() {
    Log.i(TAG, "Creating a new data insert request.");

    // [START build_insert_data_request]
    // Set a start and end time for our data, using a start time of 1 hour before this moment.
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    long endTime = cal.getTimeInMillis();
    cal.add(Calendar.HOUR_OF_DAY, -1);
    long startTime = cal.getTimeInMillis();

    // Create a data source
    DataSource dataSource = new DataSource.Builder()
            .setAppPackageName(this)
            .setDataType(DataType.TYPE_HYDRATION)
            .setStreamName(TAG + " - waterConsumed")
            .setType(DataSource.TYPE_RAW)
            .build();

    // Create a data set
    float waterConsumed = 0.3f;
    DataSet dataSet = DataSet.create(dataSource);
    // For each data point, specify a start time, end time, and the data value -- in this case,
    // the number of new steps.
    DataPoint hydration = DataPoint.create(dataSource);
    hydration.setTimestamp(cal.getTimeInMillis(), TimeUnit.MILLISECONDS);
    hydration.getValue(Field.FIELD_VOLUME).setFloat(waterConsumed);
    dataSet.add(hydration);
    // [END build_insert_data_request]

    return dataSet;
}

As of now I am only trying to first upload the data. I have commented all the data querying part.

Also, when I insert the data first time, I am getting back the status that insertion failed, but it does not happen when I try to insert again and after. You can see the log messages here:

     06-30 00:09:21.416 10294-10294/com.polkapolka.bluetooth.le I/DeviceControlActivity: Connected!!!
    06-30 00:09:21.422 10294-12719/com.polkapolka.bluetooth.le I/DeviceControlActivity: Creating a new data insert request.
    06-30 00:09:21.457 10294-12719/com.polkapolka.bluetooth.le I/DeviceControlActivity: Inserting the dataset in the History API.
    06-30 00:09:21.457 10294-12719/com.polkapolka.bluetooth.le W/Fit: Inserting the dataset in the HISTORY api
    06-30 00:09:22.929 10294-12719/com.polkapolka.bluetooth.le I/DeviceControlActivity: There was a problem inserting the dataset.
    06-30 00:09:22.929 10294-12719/com.polkapolka.bluetooth.le W/Fit: Error inserting data
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le D/ViewRootImpl: doProcessInputEvents ViewRoot{81b6602 com.polkapolka.bluetooth.le/com.polkapolka.bluetooth.le.DeviceControlActivity,ident = 1}
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le D/View: Touch up dispatch to android.widget.Button{f043f11 VFED..C.. ...P.... 453,0-645,144 #7f0c0091 app:id/btn_fit}, event = MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=40.51526, y[0]=64.24573, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=150185425, downTime=150185381, deviceId=3, source=0x1002 }
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le D/SettingsInterface:  from settings cache , name = sound_effects_enabled , value = 1
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le W/Fit: calling buildFitness
    06-30 00:09:40.164 10294-10294/com.polkapolka.bluetooth.le W/Fit: inside buildFitness
    06-30 00:10:13.225 10294-10294/com.polkapolka.bluetooth.le D/ViewRootImpl: doProcessInputEvents ViewRoot{81b6602 com.polkapolka.bluetooth.le/com.polkapolka.bluetooth.le.DeviceControlActivity,ident = 1}
    06-30 00:10:13.225 10294-10294/com.polkapolka.bluetooth.le D/View: Touch up dispatch to android.widget.Button{f043f11 VFED..C.. ...P.... 453,0-645,144 #7f0c0091 app:id/btn_fit}, event = MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=89.46991, y[0]=74.24048, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=150218486, downTime=150218460, deviceId=3, source=0x1002 }
    06-30 00:10:13.226 10294-10294/com.polkapolka.bluetooth.le D/SettingsInterface:  from settings cache , name = sound_effects_enabled , value = 1
    06-30 00:10:13.226 10294-10294/com.polkapolka.bluetooth.le W/Fit: calling buildFitness
    06-30 00:10:13.226 10294-10294/com.polkapolka.bluetooth.le W/Fit: inside buildFitness
06-30 00:20:03.346 10294-10294/com.polkapolka.bluetooth.le V/InputMethodManager: START INPUT: android.widget.NumberPicker$CustomEditText{1734323 VFED..CL. .F...... 0,38-192,111 #102038b android:id/numberpicker_input} ic=com.android.internal.widget.EditableInputConnection@347dd7a tba=android.view.inputmethod.EditorInfo@170a92b controlFlags=#100
06-30 00:20:03.378 10294-10294/com.polkapolka.bluetooth.le I/Activity: [AppLaunch] activity.onPause +
06-30 00:20:03.413 10294-10294/com.polkapolka.bluetooth.le I/Activity: [AppLaunch] activity.onPause -

Basically, after the second request to insert data, it seems it does not go in to the insertFitnessData() at all.

EDIT 1: I realized that I dont need to call BuildFitness() method everytime. So it is called only once during onCreate() and as you see in the log messages, it says "connected" to fit services.

Now I trigger the InsertandVerifyDataTask asynctask on a button onclick() and everytime the data insertion fails.

EDIT 2 I tried inserting steps data as given in their github page and that works. But Hydration isnt.

Can someone please help me out? Thanks :D


Solution

  • Make sure that you have added the new Scope(Scopes.FITNESS_NUTRITION_READ_WRITE) in requestScopes in GoogleSignInOptions.Builder. Datatype TYPE_HYDRATION belongs to the scope FITNESS_NUTRITION. The app also needs to be uninstalled and reinstalled to add the new scope to the account. You may check this link.