安卓==>偏爱?
我的应用程序因以下代码中的空指针异常而崩溃。 我在 res/xml/defaults.xml 下有一个 xml 首选项文件 知道为什么会崩溃吗?
public class Preference extends Activity {
public Preference()
{
}
public String getPreference(String key)
{
//it still crashes here
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String result = settings.getString(key, null);
return result;
}
}
my app crashes with a null pointer exception on the code below.
i have an xml preference file under res/xml/defaults.xml
Any idea why it's crashing?
public class Preference extends Activity {
public Preference()
{
}
public String getPreference(String key)
{
//it still crashes here
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String result = settings.getString(key, null);
return result;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首选项文件不存储在项目的
/res/xml/defaults.xml
中,它们存储在设备上您的应用程序文件夹中,例如
尝试不要指定文件名,如你会遇到一些首选项文件的问题,就像这个OP有 这里
那么你可能需要查询
Preference files are not storead in project's
/res/xml/defaults.xml
They are stored on the device in your application folder something like
Try do not specify the file name, as you will have some problems with the preference files, like this OP had here
Then you will probably have to query
这是一个示例代码,展示了如何保存和检索首选项。在这里,我将用户名和密码保存在 SharedPreferences 中。
从 SharedPreferences 中检索另一个活动中的用户名和密码。
希望有帮助..
Here's a sample code which shows how to save and retrieve Preferences. Here I am saving username and password in SharedPreferences.
Retrieving username and password in another activity from SharedPreferences.
Hope it helps..
在共享首选项中设置值:
从另一个活动获取值:
如果您使用某些预定义的处理程序(例如
getString(R.string._key)
)而不是访问该变量,那就太好了硬编码字符串“key”
。Setting a value in the shared preferences:
Getting the value from another activity:
It would be nice if you access the variable by using some predefined handler, such as
getString(R.string._key)
, instead of the hardcoded string"key"
.您的首选项应扩展 PreferenceActivity。然后,您需要为首选项创建一个资源 xml 文件,并在 PreferenceActivity 中引用该文件,如下所示:
首选项 xml 应该有一个 PreferenceScreen 作为顶级元素,并且您可以利用 Android 提供的所有不同的首选项视图用于设置首选项。这将是最常见、最优雅的方法。
Your Preferences should extend PreferenceActivity. Then you need to create a resource xml file for preferences, and reference that in your PreferenceActivity like so:
The preferences xml should have a PreferenceScreen as the top level element, and you can take advantage of all the different preference views Android makes available to you for setting preferences. This would be the most common, and elegant way to do it.