来自自定义edittext上下文的getsharedpreferences

时间:2011-08-20 22:31:39

标签: android preferences android-context

我有一个自定义的edittext类,我想从prefs xml中检索一些sharedpref值。我目前正在构造函数上传递上下文并运行getsharedpreferences。但是这会使应用程序崩溃。我如何从那里读取价值?

代码段:

public class RichEditText extends EditText {
        Context acontext;
        SharedPreferences synpref;
    public RichEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        acontext=context;
        synpref = acontext.getSharedPreferences("synexp", 0);
        Log.v("MyApp",synpref.getString("exp", "value"));
    }
} 

logcat的:

  

08-20 20:57:06.580:ERROR / AndroidRuntime(13343):java.lang.RuntimeException:无法启动活动ComponentInfo {com.eyecreate / com.eyecreate.MyActivity}:android.view.InflateException:Binary XML文件行#21:错误膨胀类com.eyecreate.RichEditText
  08-20 20:57:06.580:ERROR / AndroidRuntime(13343):引起:java.lang.reflect.InvocationTargetException 08-20 20:57:06.580:ERROR / AndroidRuntime(13343):引起:java.lang.NullPointerException Null指针异常与getSharedPreferences

一致

1 个答案:

答案 0 :(得分:1)

您可以尝试this。这样您就可以从代码的任何部分获得首选项。