I am not getting weekly data from google fit (Yes, There is data in google fit which I have track using watch), but Yes I am getting today's date data.
I am attaching code snippet.
Start date = "2022-09-13T00:00:00Z"
End date = "2022-09-20T23:59:59Z"
private fun readSleepSessions(startTime : Long , endTime : Long) {
val client = Fitness.getSessionsClient(requireContext(), getGoogleAccount())
val sessionReadRequest = SessionReadRequest.Builder()
.read(DataType.TYPE_SLEEP_SEGMENT)
.includeSleepSessions()
.readSessionsFromAllApps()
.enableServerQueries()
.setTimeInterval(1663027200000, 1663718399000, TimeUnit.MILLISECONDS)
.build()
client.readSession(sessionReadRequest)
.addOnSuccessListener {
Log.d(TAG, "readSleepSessions: $sessionReadRequest")
dumpSleepSessions(it)
}
.addOnFailureListener {
Log.e("MainScreen", "Unable to read sleep sessions", it)
}
}
private fun dumpSleepSessions(response: SessionReadResponse) {
if (response.sessions.isNotEmpty()){
for (session in response.sessions) {
dumpSleepSession(session, response.getDataSet(session))
Log.d(TAG, "dumpSleepSessions: ${response.sessions}")
}
}else{
Log.d(TAG, "dumpSleepSessionsResponse: ${response.status}")
}
}
private fun dumpSleepSession(session: Session, dataSets: List<DataSet>) {
dumpSleepSessionMetadata(session)
dumpSleepDataSets(dataSets)
}
private fun dumpSleepDataSets(dataSets: List<DataSet>) {
for (dataSet in dataSets) {
for (dataPoint in dataSet.dataPoints) {
val sleepStageOrdinal = dataPoint.getValue(Field.FIELD_SLEEP_SEGMENT_TYPE).asInt()
val sleepStage = sleepTargetName[sleepStageOrdinal]
val durationMillis =
dataPoint.getEndTime(TimeUnit.MILLISECONDS) - dataPoint.getStartTime(TimeUnit.MILLISECONDS)
val duration = TimeUnit.MILLISECONDS.toMinutes(durationMillis)
Log.d(TAG, "\t$sleepStage: $duration (minutes)")
}
}
Related
I am trying to display data on two different fragments from viewmodels: Recent Races and Upcoming Races. i wrote a filter function to filter the races that are yet to start and the ones that finished. Upcoming races works perfectly, when there is a change in api endpoint it removes the race from upcoming races list. but the problem is that it wont add it to recent races.
here is my code in RecentRacesViewModel
private fun getDetails() {
getRaceDetailsUseCase().onEach { result ->
when (result) {
is Resource.Success -> {
val filteredList = result.data.filter {
val time = Calendar.getInstance().time
val formatterCurrentTime = SimpleDateFormat("yyyy-MM-dd")
val formatterNow = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val currentTime = formatterCurrentTime.format(time)
val dateNow = LocalDate.parse(currentTime, formatterNow)
val dateFromModel = it.date
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val date = LocalDate.parse(dateFromModel, formatter)
dateNow >= date
}
_state1.value = Resource.Success(filteredList)
}
is Resource.Error -> {
_state1.value = Resource.Error("woops!")
}
is Resource.Loading -> {
_state1.value = Resource.Loading(true)
}
}
}.launchIn(viewModelScope)
}
thanks for help
Edit: adding the UseCase:
class RaceDetailsUseCase #Inject constructor(
private val repository: RaceResultsRepository
) {
operator fun invoke(): Flow<Resource<List<RaceDomain>>> = flow {
try {
emit(Resource.Loading(true))
val raceData = repository.GetRaceResultsRepository()
emit(Resource.Success(raceData))
} catch (e: HttpException) {
Log.d("tag", "error")
} catch (e: IOException) {
Log.d("tag", "io error")
}
}
}
Scope Approved Name : .../auth/fitness.sleep.read
Not able to fetch sleep hours for the day from google fit android.
val client = Fitness.getSessionsClient(this, getGoogleAccount())
val sessionReadRequest = SessionReadRequest.Builder()
.read(DataType.TYPE_SLEEP_SEGMENT)
.includeSleepSessions()
.readSessionsFromAllApps()
.setTimeInterval(periodStartMillis, periodEndMillis, TimeUnit.MILLISECONDS)
.build()
client.readSession(sessionReadRequest)
.addOnSuccessListener { response ->
for (session in response.sessions) {
val sessionStart = session.getStartTime(TimeUnit.MILLISECONDS)
val sessionEnd = session.getEndTime(TimeUnit.MILLISECONDS)
Log.i(TAG, "Sleep between $sessionStart and $sessionEnd")
// If the sleep session has finer granularity sub-components, extract them:
val dataSets = response.getDataSet(session)
for (dataSet in dataSets) {
for (point in dataSet.dataPoints) {
val sleepStageVal = point.getValue(Field.FIELD_SLEEP_SEGMENT_TYPE).asInt()
val sleepStage = SLEEP_STAGES[sleepStageVal]
val segmentStart = point.getStartTime(TimeUnit.MILLISECONDS)
val segmentEnd = point.getEndTime(TimeUnit.MILLISECONDS)
Log.i("TESTSLEEP", "\t* Type $sleepStage between $segmentStart and $segmentEnd")
}
}
}
I'm writing an android application which works with Google Fit APIs to collect daily user's step count.
I want to get my daily step count. this code return me a whole years step count.
How can I get the Google daily step Count value?
override fun onConnected(bundle: Bundle?) {
val dataSourceRequest = DataSourcesRequest.Builder()
.setDataTypes(DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setDataSourceTypes(DataSource.TYPE_RAW)
.build()
val dataSourcesResultCallback =
ResultCallback<DataSourcesResult> { dataSourcesResult ->
for (dataSource in dataSourcesResult.dataSources) {
if (DataType.TYPE_STEP_COUNT_CUMULATIVE == dataSource.dataType) {
registerFitnessDataListener(
dataSource,
DataType.TYPE_STEP_COUNT_CUMULATIVE
)
}
}
}
Fitness.SensorsApi.findDataSources(
mApiClient,
dataSourceRequest
)
.setResultCallback(dataSourcesResultCallback)
}
private fun registerFitnessDataListener(dataSource: DataSource, dataType: DataType) {
val request = SensorRequest.Builder()
.setDataSource(dataSource)
.setDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE)
.setSamplingRate(1, TimeUnit.SECONDS)
.build()
Fitness.SensorsApi.add(mApiClient, request, this)
.setResultCallback { status ->
if (status.isSuccess) {
Log.d("GoogleFit", "SensorApi successfully added")
}
}
}
override fun onDataPoint(dataPoint: DataPoint) {
for (field in dataPoint.dataType.fields) {
val value = dataPoint.getValue(field)
runOnUiThread(Runnable {
stepCounterTextView.setText("Field1: " + field.name + " Value1: " + value)
})
}
}
I replaced DataType.TYPE_STEP_COUNT_CUMULATIVE with a DataType.TYPE_STEP_COUNT_DELTA but it doesnoot work.
Visit https://developers.google.com/android/reference/com/google/android/gms/fitness/request/SessionReadRequest
for get daily step count read
I am trying to to a fairly simple unit test with mockito but having some trouble with the callback. I have been exploring several alternatives and a few seem good including co-routines and the do answer methods with mockito. I have not been able to figure out a good solution yet, any ideas ?
Here is my test ;
//Test for add 5 minutes
#Test
public void testWithArgumentWithDummyReturnObject() throws ParseException {
ParkingMeter testZone = new ParkingMeter();
testZone.setZoneId("21788");
testZone.setMeterName("Train Lot");
Date startDate = dateFormat.parse("09/10/2018 1:00 PM");
Date endDate = dateFormat.parse("09/10/2018 1:05 PM");
Date expectedOutputDate = dateFormat.parse("09/10/2018 1:05 PM");
CurrentSessionsResponse fakeResponse = new CurrentSessionsResponse();
CurrentSession fakeSession = new CurrentSession("fake","","");
fakeSession.zone = "Fake 1";
ArrayList<CurrentSession> sessionlist = new ArrayList<>();
sessionlist.add(fakeSession);
fakeResponse.parkingSessions = sessionlist;
MockRepository mockRepo = mock(MockRepository.class);
doReturn(fakeResponse).when(mockRepo).getCurrentSessions();
ExtendedVariableRateUtil variableRateUtil = new ExtendedVariableRateUtil();
variableRateUtil.init(testZone,"", 360, mockRepo);
variableRateUtil.setTime(5);
assertThat(variableRateUtil.getDidJump(), is(false));
assertThat(variableRateUtil.getCurrentCustomerTime(), is(expectedOutputDate));
}
Here is the relevant method in the class that is under test:
fun init(zone: ParkingMeter, plateNumber: String, extendedVariableRateMaxDayMinutes: Int, repository: ParkSmarterRepository) {
this.selectedZone = zone
this.plateNumber = plateNumber
this.extendedVariableRateMaxDayMinutes = extendedVariableRateMaxDayMinutes
if (selectedZone.maxTime < extendedVariableRateMaxDayMinutes * 24 * 60) {
//extendedVariableRateMaxDayJump = selectedZone.maxTime!
}
repository.getCurrentSessions { list, message ->
if (list?.size!! > 0) {
list.forEach {
if (it.zoneID == selectedZone.ZoneId && it.vehicle == plateNumber) {
isNewSession = false
var startDate = it.startTime
var endDate = it.endTime
} else {
isNewSession = true
}
}
}
setCurrentCustomerTime()
}
}
The callback function from retrofit:
fun getCurrentSessions(callback: (currentSessions: List<CurrentSession>?, message: String?) -> Unit) {
val call = ParkSmarter.apiInterface.getCurrentSessions()
call.enqueue(object : Callback<CurrentSessionsResponse> {
override fun onResponse(call: Call<CurrentSessionsResponse>, responseParkSmarter: Response<CurrentSessionsResponse>?) {
try {
callback(responseParkSmarter?.body()?.parkingSessions, responseParkSmarter?.body()?.psResponse?.Message)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
override fun onFailure(call: Call<CurrentSessionsResponse>, t: Throwable?) {
callback(null, "Network Error")
}
})
}
and the retrofit call
#Headers(HEADERS)
#GET("/api/ParkingSession")
Call<CurrentSessionsResponse> getCurrentSessions();
This code delete history in today:
val cal = Calendar.getInstance()
cal.time = Date()
val endTime = cal.timeInMillis
cal.add(Calendar.DAY_OF_YEAR, -1)
val startTime = cal.timeInMillis
val request = DataDeleteRequest.Builder()
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS)
// .addDataType(DataType.TYPE_STEP_COUNT_DELTA)
.deleteAllData ()
.deleteAllSessions ()
.build()
Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
.deleteData(request)
.addOnSuccessListener {
Log.i(TAG, "Successfully deleted today's sessions") }
.addOnFailureListener {
// The deletion will fail if the requesting app tries to delete data
// that it did not insert.
Log.i(TAG, "Failed to delete today's sessions")
}
Result : logcat show message successfully:
03-02 18:12:54.949 15978-15978/vnit.com.testrealm I/StepCounter: Successfully deleted today's sessions
But i use function read data, it still exist:
private fun readData() {
Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
.readDailyTotal(DataType.TYPE_STEP_COUNT_DELTA)
.addOnSuccessListener { dataSet ->
val total = (if (dataSet.isEmpty)
0
else
dataSet.dataPoints[0].getValue(Field.FIELD_STEPS).asInt()).toLong()
Log.i(TAG, "Total steps: " + total)
txtStep.setText(total.toString())
}
.addOnFailureListener(
object : OnFailureListener {
override fun onFailure(e: Exception) {
Log.w(TAG, "There was a problem getting the step count.", e)
}
})
}
I am trying to open Google fit app, it still display's old value.
Why can't delete old history?
Thanks all.