Delete data

You can also delete data, inserted by you into Samsung Health, using:

  • HealthDataStore.deleteData()

To build a delete request, it is necessary to specify the data type of the data to be deleted with it.

Remember that you can delete only the data you have inserted. Otherwise, when trying to delete the data from another app source (e.g., recorded by Samsung Health), you will get an AuthorizationException with an error code 2002: ERR_NO_OWNERSHIP_TO_WRITE.

For more details regarding exceptions and error handling please refer to com.samsung.android.sdk.health.data.error package of the SDK’s API Reference.

Below, there is an example of deleting the latest blood glucose data. To retrieve uid of the latest blood glucose data, build a read request using ReadSourceFilter in order get data inserted by the app. Additionally, utilize setOrdering() and setLimit() to obtain the latest data .Below, there is an example of deleting the latest blood glucose data.

suspend fun readLatestBloodGlucoseUid(appName: String): String {
    val healthDataStore = HealthDataService.getStore(applicationContext)
    var latestBloodGlucoseUid = ""
    val sourceFilter = ReadSourceFilter.fromApplicationId(appName)
    val readRequest = DataTypes.BLOOD_GLUCOSE.readDataRequestBuilder
        .setSourceFilter(sourceFilter)
        .setOrdering(Ordering.DESC)
        .setLimit(1)
        .build()

    try {
        val readResponse = healthDataStore.readData(readRequest)
        val responseDataList = readResponse.dataList

        if (responseDataList.isNotEmpty()) {
            latestBloodGlucoseUid = responseDataList.first().uid
        }
    } catch (e: Exception) {
        // handle possible exceptions
        e.printStackTrace()
    }

    return latestBloodGlucoseUid
}

If we successfully obtained uid, we can use it to delete the data by making a delete request with applied IdFilter.

suspend fun deleteBloodGlucoseData(bloodGlucoseUid: String) {
    val healthDataStore = HealthDataService.getStore(applicationContext)
    val idFilter = IdFilter.fromDataUid(bloodGlucoseUid)
    val deleteRequest = DataTypes.BLOOD_GLUCOSE.deleteDataRequestBuilder
        .setIdFilter(idFilter)
        .build()

    try {
        healthDataStore.deleteData(deleteRequest)
    } catch (e: Exception) {
        // handle possible exceptions
        e.printStackTrace()
    }
}