试图动态禁用preference当空指针 [英] Null Pointer when trying to dynamically disable a preference
问题描述
我收到的米preference =(preference)一个空指针异常...
在以下code(即调试在米preference
显示空; NB关键在于非空,我可以用文字代替,它仍然给了我同样的除外):
I am getting a null pointer exception on mPreference = (Preference)...
in the following code (i.e. with debugger on, mPreference
shows null; NB key is non-null, I can substitute with a literal and it still gives me the same exception):
public class SettingsManager extends PreferenceActivity {
private Preference mPreference;
private static boolean toggle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the XML preferences file
addPreferencesFromResource(R.xml.preferences);
}
public void setPrefEnabled(Context context, String key, String enabled) {
if (enabled.contentEquals("true")) {
toggle = true;
} else {
toggle = false;
}
mPreference = (Preference) getPreferenceScreen().findPreference(key);
mPreference.setEnabled(toggle);
}
}
类是由以下code调用,在一个类中的 applySettings
方法,其中设定管理
在构造函数中实例化:
The class is being called by the following code, in the applySettings
method of a class where settingsManager
is instantiated in the constructor:
public class ConfigurationSetter {
private static Context mContext;
private static SettingsManager settingsManager;
public ConfigurationSetter(Context context) {
mContext = context;
settingsManager = new SettingsManager();
}
private static void applySettings(Context context, String key,
String value, String enabled) {
settingsManager.setPrefEnabled(mContext, key, enabled);
}
}
我一直在抓我在这头,但可能有点太累了,弄明白我自己。任何帮助是AP preciated。
I've been scratching my head on this but may be a little too tired to figure it out on my own. Any help is appreciated.
与此相关的问题,我asked这里有关意图是否为这项活动所需的instantiater的问题。
Related to this problem, I asked a question here about whether intents are the required instantiater for this activity.
推荐答案
您的onCreate
方法永远不会在这个code称为(因此 preferenceScreen
在通话期间,不填充添加preferencesFromResource
像预想的那样)。 的onCreate
是活动
生命周期,如果你启动你的活动它被调用的一部分code>使用
意图
。人们通常不会使用创建活动新
,在这种情况下,它们不会链接到正确的上下文
和显示其他形式的未定义行为,像你这样的。
Your onCreate
method is never called in this code (and thus the PreferenceScreen
is not filled during the call to addPreferencesFromResource
as supposed). onCreate
is a part of the Activity
lifecycle which gets called if you launch your Activity
using an Intent
. One usually does not create Activities using new
, as in that case they don't get linked to the proper Context
and display other forms of undefined behaviour, like yours.
这篇关于试图动态禁用preference当空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!