目录

Managing Health and Fitness Sampling Data

After integrating Health Service Kit, your app is able to call the following APIs in DataController to perform operations on health and fitness data:

Before calling the preceding APIs, you need to initialize a DataController object, such as dataController, and call the API of the dataController object to handle user data. The sample code for initializing a DataController object is as follows:

// Note:
// 1. this refers to an Activity object.
// 2. Initialize objects of the DataController class each time before API calling. Otherwise, data reading may fail due to expired Activity or Context.
DataController dataController = HuaweiHiHealth.getDataController(this); // this indicates an Activity object.
  1. Before calling APIs provided by the Health Service Kit SDK, make sure that the phone screen is on. Otherwise, API calling may fail with the error code DISABLE_DATA_OPERATION. For details, please refer to error codes.
  2. Before calling APIs provided by the Health Service Kit SDK, make sure that your app runs in the foreground, or is bound with a foreground app. Otherwise, API calling may fail with the error code APPLICATION_NOT_FORGROUND. For details, please refer to error codes.
  3. In this development guide, data types DT_CONTINUOUS_STEPS_DELTA (incremental step count) and DT_INSTANTANEOUS_HEIGHT (height) are used as examples. Only the read and write scopes of these two data types are obtained for the initialized DataController object. In the following description, the context variable is an object of the android.content.Context class, which is an abstract implementation class provided by Android. You need to obtain the corresponding object based on the specific scenario.
  4. If the Activity object (called in scenarios where app UIs are included) is passed when HuaweiHiHealth.getDataController is used to obtain the DataController object, the HMS Core (APK) version can be updated forcibly; if the Context object (called in scenarios where app UIs are not included), the HMS Core (APK) cannot be updated forcibly.
  5. Learn how to call APIs provided by the Health Service Kit SDK for Android by referring to Example of Calling APIs of the Health Service Kit SDK for Android before API calling.

Inserting the User's Health and Fitness Data

The start time and end time of the sampling points of the inserted health and fitness data must be later than the UNIX timestamp corresponding to January 1, 2014.

  1. Build a data collector object.
  2. Create a sampling dataset based on the data collector.
  3. Build the start time, end time, and incremental step count for the DT_CONTINUOUS_STEPS_DELTA sampling point.
  4. Build a sampling point for incremental step count.
  5. Save a sampling point of incremental step count to the sampling dataset. You can repeat steps 3 to 5 to add more sampling points to the sampling dataset.
  6. Call the insert API to insert the sampling dataset into Health Service Kit.
  7. Register a listener to return the insertion result, as calling the insert API to insert the sampling dataset is an asynchronous operation.

    Sample code for inserting the user's health and fitness data into Health Service Kit:
    // Step 1: Build a data collector object.
    DataCollector dataCollector = new DataCollector.Builder().setPackageName(getApplicationContext())
        .setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
        .setDataStreamName("STEPS_DELTA")
        .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
        .build();
    
    // Step 2: Create a sampling dataset based on the data collector.
    final SampleSet sampleSet = SampleSet.create(dataCollector);
    
    // Step 3: Build the start time, end time, and incremental step count for a DT_CONTINUOUS_STEPS_DELTA sampling point.
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startDate = null;
    Date endDate = null;
    try {
        // Set the start time and end time, which will be stored in the standard UNIX timestamp format and are time zone independent.
         // Note that the start time and end time of the sampling points of the inserted health and fitness data must be later than the UNIX timestamp corresponding to January 1, 2014, and the interval between the start time and end time must be greater than 1 minute.
        startDate = dateFormat.parse("2020-03-17 09:00:00");
        endDate = dateFormat.parse("2020-03-17 09:05:00");
    } catch (ParseException e) {
        logger("Time parsing error");
    }
    int stepsDelta = 200;
    
    // Step 4: Build a sampling point for incremental step count.
    SamplePoint samplePoint = sampleSet.createSamplePoint()
        .setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS);
    samplePoint.getFieldValue(Field.FIELD_STEPS_DELTA).setIntValue(stepsDelta);
    // If the written step count data needs to be displayed on the home screen of the Huawei Health app, use addMetadata to add the following metadata to the sampling points:
    samplePoint.addMetadata("motion_type", "RUN");
    
    // Step 5: Save a DT_CONTINUOUS_STEPS_DELTA sampling point to the sampling dataset. You can repeat steps 3 to 5 to add more sampling points to the sampling dataset.
    sampleSet.addSample(samplePoint);
    
    // Step 6: Call the insert API to insert the sampling dataset into Health Service Kit.
    Task<Void> insertTask = dataController.insert(sampleSet);
    
    // Step 7: Register a listener to return the insertion result, as calling the insert API to insert the sampling dataset is an asynchronous operation.
    insertTask.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            logger("Successfully insert a SampleSet into HMS core");
            showSampleSet(sampleSet);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.i("DataController","Failed to insert the sample set into the HMS core:" + e.getMessage());
        }
    });

    In the preceding code snippet, two helper functions are used: showSampleSet (SampleSet sampleSet) and logger(String string). The former is used to display data returned by Health Service Kit, and the latter is used to save the output results to the log. The sample code for these two functions is as follows:

    /**
     * Print SamplePoint in the SampleSet object as an output.
     *
    * @param sampleSet Sampling dataset
     */
    private void showSampleSet(SampleSet sampleSet) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        for (SamplePoint samplePoint : sampleSet.getSamplePoints()) {
            logger("Sample point type: " + samplePoint.getDataType().getName());
            logger("Start: " + dateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
            logger("End: " + dateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
            for (Field field : samplePoint.getDataType().getFields()) {
                logger("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field));
            }
        }
    }
    
    /**
     * Send operation result logs to the logcat.
     *
     * @param string Log string
     */
    private void logger(String string) {
        Log.i("DataController", string);
    }

Deleting the User's Health and Fitness Data

Only historical data that has been inserted by your app can be deleted from Health Service Kit.

  1. Build the condition for data deletion: a data collector object.
  2. Build the time range for the deletion: start time and end time.
  3. Build a parameter object for the deletion.
  4. Call delete to delete the sampling dataset based on the specified condition.
  5. Register a listener to return the deletion result, as calling delete to delete the sampling dataset is an asynchronous operation.

    // Step 1: Build the condition for data deletion: a data collector object.
    DataCollector dataCollector = new DataCollector.Builder().setPackageName(getApplicationContext())
        .setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
        .setDataStreamName("STEPS_DELTA")
        .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
        .build();
    
    // Step 2: Build the time range for the deletion: start time and end time.
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startDate = null;
    Date endDate = null;
    try {
        // Set the start time and end time, which will be stored in the standard UNIX timestamp format and are time zone independent.
        startDate = dateFormat.parse("2020-03-17 09:00:00");
        endDate = dateFormat.parse("2020-03-17 09:05:00");
    } catch (ParseException e) {
        logger("Time parsing error");
    }
    
    // Step 3: Build a parameter object for the deletion.
    DeleteOptions deleteOptions = new DeleteOptions.Builder().addDataCollector(dataCollector)
        .setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS)
        .build();
    
    // Step 4: Call the delete API to delete the sampling dataset based on the specified condition.
    Task<Void> deleteTask = dataController.delete(deleteOptions);
    
    // Step 5: Register a listener to return the deletion result, as calling the delete API to delete the sampling dataset is an asynchronous operation.
    deleteTask.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            logger("Successfully delete sample data from HMS core");
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.i("DataController","Failed to delete sample data from HMS core:" + e.getMessage());
        }
    });

    In the preceding code, a helper function is used: logger(String string), which stores the output results. The sample code for the function is as follows:

    /**
     * Send operation result logs to the logcat.
     *
     * @param string Log string
     */
    private void logger(String string) {
        Log.i("DataController", string);
    }

Updating the User's Health and Fitness Data

Note that the start time and end time of the range for updating the health and fitness data must be later than the UNIX timestamp corresponding to January 1, 2014.

  1. Build the condition for data update: a data collector object.
  2. Build a sampling dataset for the update based on the data collector.
  3. Build the start time, end time, and incremental step count for a DT_CONTINUOUS_STEPS_DELTA sampling point for the update.
  4. Build a sampling point for updating the incremental step count.
  5. Add a sampling point for updating the incremental step count to the sampling dataset. You can repeat steps 3 to 5 to add more sampling points to the sampling dataset.
  6. Build a parameter object for the update.
  7. Call the update API to update the sampling dataset based on the specified parameter object.
  8. Register a listener to return the update result, as calling the update API to update the sampling dataset is an asynchronous operation.

    // Step 1: Build the condition for data update: a data collector object.
    DataCollector dataCollector = new DataCollector.Builder().setPackageName(getApplicationContext())
        .setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
        .setDataStreamName("STEPS_DELTA")
        .setDataGenerateType(DataCollector.DATA_TYPE_RAW)
        .build();
    
    // Step 2: Build the sampling dataset for the update based on the data collector.
    SampleSet sampleSet = SampleSet.create(dataCollector);
    
    // Step 3: Build the start time, end time, and incremental step count for a DT_CONTINUOUS_STEPS_DELTA sampling point.
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startDate = null;
    Date endDate = null;
    try {
        // Set the start time and end time, which will be stored in the standard UNIX timestamp format and are time zone independent.
        // Note that the start time and end time of the range for updating the health and fitness data must be later than the UNIX timestamp corresponding to January 1, 2014.
        startDate = dateFormat.parse("2020-03-17 09:00:00");
        endDate = dateFormat.parse("2020-03-17 09:05:00");
    } catch (ParseException exception) {
        logger("Time parsing error");
    }
    int stepsDelta = 200;
    
    // Step 4: Build a sampling point for updating the incremental step count.
    SamplePoint samplePoint = sampleSet.createSamplePoint()
        .setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS);
    samplePoint.getFieldValue(Field.FIELD_STEPS_DELTA).setIntValue(stepsDelta);
    // If the updated step count data needs to be displayed on the home screen of the Huawei Health app, use addMetadata to add the following metadata to the sampling points:
    samplePoint.addMetadata("motion_type", "RUN");
    
    // Step 5: Add a sampling point for updating the incremental step count to the sampling dataset. You can repeat steps 3 to 5 to add more sampling points to the sampling dataset.
    sampleSet.addSample(samplePoint);
    
    // Step 6: Build a parameter object for the update operation.
    UpdateOptions updateOption = new UpdateOptions.Builder()
        .setTimeInterval(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS)
        .setSampleSet(sampleSet)
        .build();
    
    // Step 7: Call the update API to update the sampling dataset based on the specified parameter object.
    Task<Void> updateTask = dataController.update(updateOption);
    
    // Step 8: Register a listener to return the update result, as calling the update API to update the sampling dataset is an asynchronous operation.
    updateTask.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            logger("Successfully update sample data from HMS core");
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.i("DataController","Failed to update sample data from HMS core:" + e.getMessage());
        }
    });

    In the preceding code, a helper function is used: logger(String string), which stores the output results. The sample code for the function is as follows:

    /**
     * Send operation result logs to the logcat.
     *
     * @param string Log string
     */
    private void logger(String string) {
        Log.i("DataController", string);
    }

Querying the User's Health and Fitness Data

To query historical data from Health Service Kit, for example, to query the number of steps taken within a period of time, you can specify the criteria in ReadOptions. For example, you can specify the data collector, data type, and detailed data.

  1. The start time and end time passed for querying the health and fitness data must be later than the UNIX timestamp corresponding to January 1, 2014.
  2. The start time and end time for querying cannot span over 31 days.
  3. If no step count detailed data is found, please refer to What can I do if no data is found when I query the step count details? to troubleshoot.
  1. Build the time range for the query: start time and end time.
  2. Build the object of the query condition.
  3. Call the read API to query the sampling dataset based on the specified query condition object.
  4. Register a listener to monitor the query result, as calling the read API to query the sampling dataset is an asynchronous operation.

    // Step 1: Build the time range for the query: start time and end time.
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startDate = null;
    Date endDate = null;
    try {
        // Set the start time and end time, which will be stored in the standard UNIX timestamp format and are time zone independent.
        // Note that the start time and end time of the range for querying the health and fitness data must be later than the UNIX timestamp corresponding to January 1, 2014.
        startDate = dateFormat.parse("2020-03-17 09:00:00");
        endDate = dateFormat.parse("2020-03-17 09:05:00");
    } catch (ParseException exception) {
        logger("Time parsing error");
    }
    
    // Step 2: Build the object of the query condition.
    // Set DataType.DT_CONTINUOUS_STEPS_DELTA to query the user's step count data.
    ReadOptions readOptions = new ReadOptions.Builder().read(DataType.DT_CONTINUOUS_STEPS_DELTA)
        .setTimeRange(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS)
        .build();
    
    // Step 3: Call the read API to query the sampling dataset based on the specified query condition object.
    Task<ReadReply> readReplyTask = dataController.read(readOptions);
    
    // Step 4: Register a listener to monitor the query result, as calling the read API to query the sampling dataset is an asynchronous operation.
    readReplyTask.addOnSuccessListener(new OnSuccessListener<ReadReply>() {
        @Override
        public void onSuccess(ReadReply readReply) {
            logger("Successfully read a SampleSet from HMS core");
            for (SampleSet sampleSet : readReply.getSampleSets()) {
                showSampleSet(sampleSet);
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.i("DataController","Failed to read a SampleSet from HMS core:" + e.getMessage());
        }
    });

    In the preceding code snippet, two helper functions are used: showSampleSet (SampleSet sampleSet) and logger(String string). The former is used to display data returned by Health Service Kit, and the latter is used to save the output results to the log. The sample code for these two functions is as follows:

    /**
     * Print SamplePoint in the SampleSet object as an output.
     *
    * @param sampleSet Sampling dataset
     */
    private void showSampleSet(SampleSet sampleSet) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        for (SamplePoint samplePoint : sampleSet.getSamplePoints()) {
            logger("Sample point type: " + samplePoint.getDataType().getName());
            logger("Start: " + dateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
            logger("End: " + dateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
            for (Field field : samplePoint.getDataType().getFields()) {
                logger("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field));
            }
        }
    }
    
    /**
     * Send operation result logs to the logcat.
     *
     * @param string Log string
     */
    private void logger(String string) {
        Log.i("DataController", string);
    }

Querying the User's Health and Fitness Statistics of the Current Day

For details about the supported data types, please refer to the input parameter description of readTodaySummation.

  1. Call readTodaySummation with the specified data type (incremental step count: DT_CONTINUOUS_STEPS_DELTA) to query the statistics of the data type on the current day.
  2. Register a listener to monitor the data query result, as calling the readTodaySummation API to query the statistics of the current day is an asynchronous operation.

    This API is used to query the statistics of a certain data type on the current day. The query time range starts from 00:00:00 of the day and ends at the system timestamp when the API is called. Calculation will be performed on all data points with the start time or end time being in the specified time range, and the statistical results will be returned. Only the preceding data types are supported.

    // Step 1: Call readTodaySummation with the specified data type (incremental step count: DT_CONTINUOUS_STEPS_DELTA) to query the statistics of the data type on the current day.
    Task<SampleSet> todaySummationTask = dataController.readTodaySummation(DataType.DT_CONTINUOUS_STEPS_DELTA);
    
    // Step 2: Register a listener to monitor the data query result, as calling the readTodaySummation API to query the statistics of the current day is an asynchronous operation.
    todaySummationTask.addOnSuccessListener(new OnSuccessListener<SampleSet>() {
        @Override
        public void onSuccess(SampleSet sampleSet) {
            logger("Successfully read today summation from HMS core");
            if (sampleSet != null) {
                showSampleSet(sampleSet);
            }
        }
    });
    todaySummationTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.i("DataController","Failed to read today summation from HMS core:" + e.getMessage());
        }
    });

    In the preceding code snippet, two helper functions are used: showSampleSet (SampleSet sampleSet) and logger(String string). The former is used to display data returned by Health Service Kit, and the latter is used to save the output results to the log. The sample code for these two functions is as follows:

    /**
     * Print SamplePoint in the SampleSet object as an output.
     *
    * @param sampleSet Sampling dataset
     */
    private void showSampleSet(SampleSet sampleSet) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        for (SamplePoint samplePoint : sampleSet.getSamplePoints()) {
            logger("Sample point type: " + samplePoint.getDataType().getName());
            logger("Start: " + dateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
            logger("End: " + dateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
            for (Field field : samplePoint.getDataType().getFields()) {
                logger("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field));
            }
        }
    }
    
    /**
     * Send operation result logs to the logcat.
     *
     * @param string Log string
     */
    private void logger(String string) {
        Log.i("DataController", string);
    }

Querying the User's Health and Fitness Statistics of Multiple Days

The API is used to query the daily statistics of a certain data type of multiple days. The query time range is specified by the start time and end time (unit: day) passed as input parameters.

All queried data points within the specified time range will be grouped by day. The statistical calculation will be performed on each data group (for each day), and the daily statistical results of the involved days will be returned.

  1. For details about the supported data types, please refer to the input parameter description of readDailySummation.
  2. The start time and end time for querying must be later than January 1, 2014 (represented by 20140101).
  3. The start time and end time for querying cannot span over 31 days.
  1. Initialize the start time and end time, in the format of YYYYMMDD.
  2. Call the readDailySummation API to query the statistics of multiple days, of the specified data type (incremental step count) within the specified time range.
  3. Register a listener to return the data query result, as calling the readDailySummation API to query the daily statistics of multiple days is an asynchronous operation.

    // Step 1: Initialize the start time and end time, in the format of YYYYMMDD.
    // Note that the start time and end time must be later than January 1, 2014.
    int startTime = 20200818;
    int endTime = 20200825;
    
    // Step 2: Call the readDailySummation API to query the statistics of multiple days, of the specified data type (incremental step count) within the specified time range.
    Task<SampleSet> daliySummationTask = dataController.readDailySummation(DataType.DT_CONTINUOUS_STEPS_DELTA, startTime, endTime);
    
    // Step 3: Register a listener to return the data query result, as calling the readDailySummation API to query the daily statistics of multiple days is an asynchronous operation.
    daliySummationTask.addOnSuccessListener(new OnSuccessListener<SampleSet>() {
        @Override
        public void onSuccess(SampleSet sampleSet) {
            logger("Successfully read daily summation from HMS core");
            if (sampleSet != null) {
                showSampleSet(sampleSet);
            }
        }
    });
    daliySummationTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            logger("readDailySummation" + e.toString());
        }
    });

    In the preceding code snippet, two helper functions are used: showSampleSet (SampleSet sampleSet) and logger(String string). The former is used to display data returned by Health Service Kit, and the latter is used to save the output results to the log. The sample code for these two functions is as follows:

    /**
     * Print SamplePoint in the SampleSet object as an output.
     *
    * @param sampleSet Sampling dataset
     */
    private void showSampleSet(SampleSet sampleSet) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        for (SamplePoint samplePoint : sampleSet.getSamplePoints()) {
            logger("Sample point type: " + samplePoint.getDataType().getName());
            logger("Start: " + dateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
            logger("End: " + dateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
            for (Field field : samplePoint.getDataType().getFields()) {
                logger("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field));
            }
        }
    }
    
    /**
     * Send operation result logs to the logcat.
     *
     * @param string Log string
     */
    private void logger(String string) {
        Log.i("DataController", string);
    }

Querying the User's Latest Health and Fitness Data

For details about the supported data types, please refer to the input parameter description of readLatestData.

  1. Call the readLatestData API with the specified data type (such as height: DT_INSTANTANEOUS_HEIGHT) to query the latest sampling point.
  2. Register a listener to return the data query result, as calling the readLatestData API to query the latest sampling point is an asynchronous operation.

    // Step 1: Call the readLatestData API with the specified data type (such as height: DT_INSTANTANEOUS_HEIGHT) to query the latest sampling point.
    List<DataType> dataTypes = new ArrayList<>();
    dataTypes.add(DataType.DT_INSTANTANEOUS_HEIGHT);
    Task<Map<DataType, SamplePoint>> readLatestDatas = dataController.readLatestData(dataTypes);
    
    // Step 2: Register a listener to return the data query result, as calling the readLatestData API to query the latest sampling point is an asynchronous operation.
    readLatestDatas.addOnSuccessListener(new OnSuccessListener<Map<DataType, SamplePoint>>() {
        @Override
        public void onSuccess(Map<DataType, SamplePoint> samplePointMap) {
            logger("Success read latest data from HMS core");
            if (samplePointMap != null) {
                for (DataType dataType : dataTypes) {
                    if (samplePointMap.containsKey(dataType)) {
                        showSamplePoint(samplePointMap.get(dataType));
                    } else {
                        logger("The DataType " + dataType.getName() + " has no latest data");
                    }
                }
            }
        }
    });
    readLatestDatas.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.i("DataController","Failed to read latest data from HMS core:" + e.getMessage());
        }
    });

    In the preceding code snippet, two helper functions are used: showSamplePoint(SamplePoint samplePoint) and logger(String string). The former is used to display data returned by Health Service Kit, and the latter is used to save the results to the log. The sample code for these two functions is as follows:

    /**
     * Print SamplePoint as an output.
     *
    * @param samplePoint Sampling dataset
     */
    private void showSamplePoint(SamplePoint samplePoint) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        logger("Sample point type: " + samplePoint.getDataType().getName());
        logger("Start: " + dateFormat.format(new Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))));
        logger("End: " + dateFormat.format(new Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))));
        for (Field field : samplePoint.getDataType().getFields()) {
            logger("Field: " + field.getName() + " Value: " + samplePoint.getFieldValue(field));
        }
        logger(System.lineSeparator());
    }
    
    /**
     * Send operation result logs to the logcat.
     *
     * @param string Log string
     */
    private void logger(String string) {
        Log.i("DataController", string);
    }

Clearing the User's Health and Fitness Data from the Device and Cloud

  1. Call clearAll to clear all the data inserted by the app from the device and cloud.
  2. Register a listener to return the data clearing result, as calling clearAll to clear user data from the device and cloud is an asynchronous operation.

    // Step 1: Call clearAll to clear all the data inserted by the app from the device and cloud.
    Task<Void> clearAllTask = dataController.clearAll();
    
    // Step 2: Register a listener to return the data clearing result, as calling clearAll to clear user data from the device and cloud is an asynchronous operation.
    clearAllTask.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            logger("clearAll success");
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.i("DataController","Failed to clear data:" + e.getMessage());
        }
    });

    In the preceding code snippet, a helper function is used: logger(String string). This is a TextView function used to save the results to the log as an output and display the results on the UI. The sample code for the function is as follows:

    /**
     * TextView to send the operation result logs to the logcat and to the UI
     *
     * @param string Log string
     */
    private void logger(String string) {
        Log.i("DataController", string);
    }