0

我正在尝试对我的源代码中的几个值进行空值检查,看来它们都返回空值。由于我的 SharedPreferences 实现,我应该能够在我的新类中使用这些值,但它似乎不起作用。(我似乎忽略了一些简单的事情。)

起点类 SharedPreferences 实现:

SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor=prefs.edit();
    editor.putBoolean("name",true);
    editor.putBoolean("cap",true);
    editor.putBoolean("code",true);
    editor.putBoolean("time",true);
    editor.putBoolean("ssid",true);
    editor.commit();

端点类 SharedPreferences 实现:

SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor=prefs.edit();
   if (new == null) {
        Log.d(TAG, "Broken Value! Debug! Debug!"); 
    prefs.getBoolean("new", true);
    prefs.getBoolean("user", true);
    prefs.getBoolean("name", true);
    prefs.getBoolean("data", true);
    prefs.getBoolean("login", true);
    editor.commit();

当我检查它们时,端点中的值显示为 null - 知道为什么吗?我相信由于我实现了 SharedPreferences,它们不应该为 null,但它们仍然返回 null。(我可以发誓我正确地实现了这个——我不知道为什么我不能检索这些值——我相信一切都应该正常运行——但奇怪的是:它不是。)

首次尝试提供的解决方案:

SharedPreferences prefs=getPreferences(NDEF_PREF, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=prefs.edit();
            prefs.getBoolean("name", true);
            prefs.getBoolean("cap", true);
            prefs.getBoolean("code", true);
            prefs.getBoolean("time", true);
            prefs.getBoolean("ssid", true);
            editor.commit();
4

1 回答 1

0

你没有得到 SharedPreferences,试试这个:

SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

PREFS_NAME你给文件起的名字在哪里。

你也不能这样做:

SharedPreferences.Editor editor=prefs.edit();
prefs.getBoolean("new", true);

由于 Editor 类没有该方法...相反,您应该使用prefs变量来获取值。

看看你在保存和恢复什么……在这两种情况下唯一的值是“名称”,所以其他的都是假的。

编辑

例子:

String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF, Context.MODE_PRIVATE);
prefs.getBoolean("name", true);
prefs.getBoolean("cap", true);
prefs.getBoolean("code", true);
prefs.getBoolean("time", true);
prefs.getBoolean("ssid", true);
于 2013-04-18T09:51:17.993 回答