【问题标题】:getsharedpreferences from custom edittext context从自定义 edittext 上下文中获取共享首选项
【发布时间】: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


【解决方案1】:

你可以试试this。通过这种方式,您可以从代码的任何部分获取首选项。

【讨论】:

    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    相关资源
    最近更新 更多