从自定义编辑文本上下文中获取共享首选项
我有一个自定义的 edittext 类,我想从首选项 xml 中检索一些共享首选项值。我目前正在获取传递给构造函数的上下文,并从中运行 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: 错误/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.InitationTargetException 08-20 20:57:06.580:错误/AndroidRuntime(13343):由以下原因引起:java.lang.NullPointerException空指针异常与 getSharedPreferences 上线
I have a custom edittext class I have made that I'd like to retrieve some sharedpref values from a prefs xml. I am currently getting the context passed on the constructor and running getsharedpreferences off that. This crashes the app, though. How would I go about reading the values from there?
Code snippet:
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: Unable to start activity ComponentInfo{com.eyecreate/com.eyecreate.MyActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class com.eyecreate.RichEditText
08-20 20:57:06.580: ERROR/AndroidRuntime(13343): Caused by: java.lang.reflect.InvocationTargetException 08-20 20:57:06.580: ERROR/AndroidRuntime(13343): Caused by: java.lang.NullPointerException The Null pointer exception was on the line with getSharedPreferences
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试这个。这样您就可以从代码的任何部分获取首选项。
You can try this. This way you can get preferences from any part of code.