Reputation: 27
Supposedly i have a sharedpreferences float value called floatValue. How do i set floatValue automatically to 0 when the device detects its a new day? Like for example today is 2/1/17, and the value of floatValue is 1250.23. Is it possible for this to be reset to 0 and that my textView will display 0 such that when the user wakes up in the morning the next day, he will notice the textview's text is 0.
I'm sorry for the indentations. Basically, I initialize newTodayFloatValue to 0 as i need todayValueToBeAdded to append into newTodayFloatValue. Then i save this value into SharedPreferences! But i'm hoping this can be resetted after date_changed.
float newTodayFloatValue = 0;
tvTodayFloatValue = (TextView)findViewById(R.id.todayfloatValueTextView);
Intent intent1 = getIntent();
float todayValueToBeAdded = intent1.getFloatExtra("strValueToBeAdded", 0.0f);
final SharedPreferences totalTodayfloatValue = getSharedPreferences("totalTodayfloatValue", 0);
newTodayFloatValue = totalTodayfloatValue.getFloat("totalTodayfloatValue", 0);
newTodayFloatValue = newTodayFloatValue + todayValueToBeAdded;
SharedPreferences.Editor editor = totalTodayfloatValue.edit();
editor.putFloat("totalTodayfloatValue", newTodayFloatValue);
editor.commit();
tvTodayFloatValue.setText(String.valueOf(newTodayFloatValue));
Upvotes: 0
Views: 166
Reputation: 3043
I think there is much easier way to achieve this effect. I would write a methods getFloatValue(...)
, and setFloatValue
, in method setFloatValue
you should update not only floatValue
in SharedPreferences
but floatValueLastModification
also.
Then in getFloatValue
you should compare floatValueLastModification
with current time and return 0 if it is previous day.
Of course since you do it this way you should access this floatValue
only through these methods.
I think it will be much easier to read and understand such code.
Upvotes: 0
Reputation: 3235
You can use a broadcast receiver with action
"android.intent.action.DATE_CHANGED"
It will trigger whenever the date is changed either automatically (because the date actually has changed) or explicitly by the user.
For this Broadcast to be received even when your app is not running, you will need to declare it within your manifest with the mentioned Intent-Filter.
<receiver
android:name=".DateChangeReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.DATE_CHANGED" />
</intent-filter>
</receiver>
Then within the Receiver, you can make a change in the SharedPreferences
public class DateChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences = context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("YOUR_INT", 0);
editor.apply();
}
}
Upvotes: 2