【发布时间】:2011-08-20 22:31:39
【问题描述】:
我有一个自定义的edittext 类,我想从prefs xml 中检索一些sharedpref 值。我目前正在获取构造函数上传递的上下文并运行 getsharedpreferences 。但是,这会使应用程序崩溃。我将如何从那里读取值?
代码sn-p:
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: 错误/AndroidRuntime(13343): java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.eyecreate/com.eyecreate.MyActivity}: android.view.InflateException: 二进制 XML文件第 21 行:膨胀类 com.eyecreate.RichEditText 时出错
08-20 20:57:06.580: 错误/AndroidRuntime(13343): 由: java.lang.reflect.InvocationTargetException 08-20 20:57:06.580: 错误/AndroidRuntime(13343): 由: java.lang.NullPointerException Null 指针异常与 getSharedPreferences 上线
【问题讨论】:
-
能贴一下异常的logcat日志吗?
-
可能
context为空? -
是的,上下文似乎为空。
-
所以传递一个真实的上下文,而不是 null...
标签: android preferences android-context