gpt4 book ai didi

Android CheckBoxPreference java.lang.StackOverflowError

转载 作者:行者123 更新时间:2023-11-30 04:17:15 26 4
gpt4 key购买 nike

我的代码中有这个 CheckBoxPreference。我在我的代码中实现了 onSharedPreferenceChanged() 来执行一些操作。问题是,当我单击复选框首选项时,该函数会在具有相同值的循环中被调用。谁能帮我解决这个问题?

以下是相关的代码 fragment :

偏好 Activity 中的 onSharedPreferenceChanged() 部分:

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();
}

偏好 Activity 的 xml 部分:

<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>

最佳答案

简单:如果您在 onSharedPreferenceChanged 中更改 SharedPreference,则会创建一个循环,因为您会触发自己。循环实际上是一个递归,如果你无休止地调用自己,你就会填满内存(不是普通的 - “堆栈”),直到你得到一个 stackoverflow。

一个正常的(有点有用的)递归看起来像这样:

public int sumAllNumbersUpTo (int number) {
if (number > 0) {
return number + sumAllNumbersUpTo(number - 1);
} else {
return 0;
}
}

int result = sumAllNumbersUpTo(3);
// result is 3 + ( 2 + ( 1 + ( 0 ) ) )

它会调用自己直到满足某些条件。如果您删除该条件,则此方法将永远不会结束。

关于Android CheckBoxPreference java.lang.StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com