I have this CheckBoxPreference in my code. I have implemented onSharedPreferenceChanged() in my code to perform some action. The problem is that when i click on the checkbox preference, the function gets called in a loop with same value. Can anyone help me with this?
Here are the relevant code snippets:
onSharedPreferenceChanged() section in preference activity:
if(key.equals(LOCATION_UPDATE_KEY)) {
boolean update = sharedPreferences.getBoolean(LOCATION_UPDATE_KEY, false);
Log.v("preferences", update + "");
editor.putBoolean(LOCATION_UPDATE_KEY, update);
editor.commit();
}
preference activity’s xml section:
<PreferenceCategory
android:title="Location">
<CheckBoxPreference
android:title="Track Location"
android:defaultValue="false"
android:summary="Keep track of handset location (Consumes Battery)"
android:key="track_option" />
<ListPreference
android:title="Location Update Source"
android:summary=""
android:key="track_source"
android:defaultValue="2"
android:entries="@array/location_sources"
android:entryValues="@array/location_sources_values"
android:dependency="track_option" />
<ListPreference
android:title="Location Update Interval"
android:summary=""
android:key="track_interval"
android:defaultValue="2"
android:entries="@array/location_update_interval"
android:entryValues="@array/location_update_interval_values"
android:dependency="track_option" />
</PreferenceCategory>
simple: if you change the SharedPreference in
onSharedPreferenceChangedyou create a loop because you trigger yourself. The loop is actually a recursion and if you call yourself endlessly you fill up the memory (not the normal one – the “stack”) until you get a stackoverflow.a normal (somewhat useful) recursion looks like this:
it is calling itself until some condition is met. If you remove that condition then this method will never end.