简体   繁体   English

Android共享偏好强制关闭

[英]Android sharedpreferences force closes

I am trying to use sharedpreferences in a PreferenceActivity, but unfortunately it force closes. 我试图在PreferenceActivity中使用sharedpreferences,但不幸的是它强制关闭。 Part of it: 一部分:

public class EditPreferences extends PreferenceActivity {

String ListPreference;
boolean CheckboxPreference;
SharedPreferences mprefs;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);


final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");

checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
public boolean onPreferenceChange(Preference preference, Object newValue) {
    if (newValue.toString().equals("true"))
    {  
        Toast.makeText(getApplicationContext(), "CB: " + "true", Toast.LENGTH_SHORT).show();
        SharedPreferences.Editor edit = mprefs.edit();
        edit.putString("cbstate", "true");
        edit.commit();
    } 
    else 
    {  
        Toast.makeText(getApplicationContext(), "CB: " + "false", Toast.LENGTH_SHORT).show();
    SharedPreferences.Editor edit = mprefs.edit(); //this line force closes
        edit.putString("cbstate", "false");
        edit.commit();
    }
    return true;
}

}); });

What is wrong with the code? 代码有什么问题? Thanks, B 谢谢,B

它看起来不像mprefs被分配了一个值(除非它发生在其他地方)

You should look at the log to see the stack crawl of the exception, which tells you why your code is crashing. 您应该查看日志以查看异常的堆栈爬网,它会告诉您代码崩溃的原因。

I am not adding this as a question for clarification, because the fact that a stack crawl is not included in the question is a strong indication that you haven't actually looked at it, and if that is the case then the answer to your question and most likely solution to your problem is to go look at that and see why it says you are crashing. 我没有将此作为澄清的问题添加,因为问题中不包含堆栈爬行这一事实强烈表明您实际上没有看过它,如果是这种情况那么问题的答案就是问题的答案并且最有可能解决你的问题的方法是去看看它,看看为什么它说你崩溃了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM