Android:PreferenceManager vs Context.getSharedPreferences() 以及为什么后者让我失望

Android: PreferenceManager vs Context.getSharedPreferences() and why the latter failed me

好的,按照 Udacity Android 开发课程,我到达了我需要访问保存到名为 pref_general.xml 的 sharedPreferences 文件中的邮政编码的部分,该文件保存了邮政编码在字符串类型中,并通过键值对连接到一个名为 location 的键。

我解决这个问题的方法是使用 getSharedPreferences() 方法按名称获取文件。虽然这似乎不会导致问题,因为文件没有变成 null,但尝试检索邮政编码导致无法通过键找到值并确定参数的给定默认值。

SharedPreferences appPreferences = getActivity().getSharedPreferences("pref_general", Context.MODE_PRIVATE);
        if(appPreferences == null) {
            Log.v("ERRORTAG", "Cannot get sharedPreferences file");
        }
        String getPostal = appPreferences.getString(getString(R.string.pref_location_key), "0");
        Log.v("ERRORTAG", getPostal);

logcat 上的第二个冗长语句导致默认字符串值 0 而不是与 94043 邮政编码的给定键绑定的值。

现在 Udacity 给出的答案是使用 PreferenceManager,它获取绑定到 Activity

的默认单独 sharedPreferences 文件
SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

文件不为空且检索到的邮政编码是在 sharedPreference 文件中设置为键值对的给定默认邮政编码 94043。

我想了解为什么我的方法不起作用;它非常接近。唯一的区别是文件的访问方式。请给我一个解释,为什么。谢谢。

PreferenceActivity 的文档说:

If you are using PreferenceActivity in its old mode, the documentation [for PreferenceFragment] applies to the deprecated APIs here.

PreferenceFragment 的文档解释了正在发生的事情:

To retrieve an instance of SharedPreferences that the preference hierarchy in this fragment will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this fragment.

这表明 PreferenceActivity#addPreferencesFromResource(...) 不会创建与原始文件同名的 SharedPreferences 文件。相反,它将文件合并到默认的共享首选项中。 pref_general 文件不存在,当您试图从中读取时,您基本上是在创建它。 (尽管在您对其进行编辑之前它实际上并未在磁盘上创建。)