Can';无法从Android中的首选项获取项目

Can';无法从Android中的首选项获取项目,android,sharedpreferences,Android,Sharedpreferences,我的res/xml文件夹中存储了preferences.xml: <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory> <Preference android:key="units_length" andro

我的res/xml文件夹中存储了preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory>
        <Preference android:key="units_length" android:title="imperial"></Preference>
    </PreferenceCategory>
</PreferenceScreen>


我的申请只是说“没什么”。我做错了什么?

尝试将首选项xml定义中的
android:defaultValue
属性设置为适当的值。属性似乎从未初始化过。

尝试将首选项xml定义中的
android:defaultValue
属性设置为任何适当的值。属性似乎从未初始化过。

嗯。。我希望它从首选项中获取单位长度,以便显示“英制”。从我的问题中我觉得这很明显。那么你应该将默认值设置为“imperial”而不是“nothing”。什么?我认为您不应该对不理解的主题发表评论。当您尝试访问不存在的首选项时,将返回默认值。您没有创建首选项,这意味着您没有调用putString(“units_length”,“imperial”),因此最简单的方法是将首选项的默认值设置为“imperial”。我确实创建了首选项,请查看上面的xml文件。嗯。。我希望它从首选项中获取单位长度,以便显示“英制”。从我的问题中我觉得这很明显。那么你应该将默认值设置为“imperial”而不是“nothing”。什么?我认为您不应该对不理解的主题发表评论。当您尝试访问不存在的首选项时,将返回默认值。您没有创建首选项,这意味着您没有调用putString(“units_length”,“imperial”),因此最简单的方法是将首选项的默认值设置为“imperial”。我创建了我的首选项,查看上面的xml文件。尝试通过调用
首选项管理器来获取
SharedReferences
对象。GetDefaultSharedReferences(this)
我已经测试了代码,它可以工作,但仅当使用
EditTextPreference
时,我没有意识到使用简单的
首选项时可能会有所不同,在这种情况下,我认为最好手动初始化您的首选项,或者在
get*()
methodsThanks中使用默认值,这样我就可以继续了。感谢您的时间。请尝试通过调用
首选项管理器来获取
SharedReferences
对象。GetDefaultSharedReferences(此)
我已经测试了代码,它可以工作,但只有在使用
EditTextPreference
时,我才意识到使用简单的
首选项时可能会有所不同,在这种情况下,我认为最好手动初始化您的首选项,或者在
get*()
methodsThanks中使用默认值,这样我就可以继续了。谢谢你抽出时间。
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.results);

// Get preferences
SharedPreferences preferences = getSharedPreferences("preferences", 0);

// Fetch the text view
TextView text = (TextView) findViewById(R.id.textView1);

// Set new text
text.setText(preferences.getString("units_length", "nothing"));

}