I'm creating a pedometer app. It is almost done, except for one thing. When day has past, I want to reset step numbers.How to implement sharedpreferences
to my code?
How can I reset step numbers?
I tried this way. But when time past every numbers turning normal value. Not starting from zero.
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor == stepCounter){
stepCount = (int) sensorEvent.values[0];
////////////////
saveSteps(stepCount);
resetStep(stepCount);
////////////////
progressBar.setProgress(stepCount);
textView.setText(String.valueOf(stepCount));
txtstepinfo.setText("Adım: " + String.valueOf(stepCount) );
///////////
progressBar.setProgress(stepCount);
Log.i("sda",String.valueOf(stepCount));
/////////////////////
txtcalinfo.setText("Kalori: "+calculateCalori(stepCount));
txtDistanceinfo.setText("Mesafe: "+calculateDistance(stepCount));
}
}
private void resetStep(int s){
Calendar date = Calendar.getInstance();
if(date.get(Calendar.HOUR) == 0 && date.get(Calendar.MINUTE) == 00 ){
editor.putInt("step",0);
editor.apply();
stepCount = 0;
txtstepinfo.setText(String.valueOf(stepCount));
}
}
private void saveSteps(int s){
editor.putInt("step",s);
editor.apply();
}
Hope my answer make it clear, i'll correct your code.
if (date.get(Calendar.HOUR) == 0 && date.get(Calendar.MINUTE) == 00 ) {
editor.putInt("step",0);
editor.apply();
stepCount = 0;
txtstepinfo.setText(String.valueOf(stepCount));
}
it means, this code is just running well when application opened at 00:00:00 - 59s. I have simple condition to reset your shared preferences, but i didn't expect it was the best answer.
val preferences by lazy { applicationContext.getSharedPreferences("KEY", MODE_PRIVATE) }
val calendar by lazy {Calendar.getInstance() }
val date by lazy { calendar.get(Calendar.DAY_OF_MONTH) } // 1 - 31
val dateKey = "DATE_NOW"
val stepKey = "STEP_COUNT"
// Check the date
if (preferences.getInt(dateKey, 0) != date) {
// Clear shared preferences
preferences.edit { clear() }
// Persistent the date
preferences.edit { putInt(dateKey, date) }
}
val myStep = preferences.getInt(stepKey, 0)
preferences.edit { putInt(stepKey, myStep + 1) }