【发布时间】:2013-05-04 01:42:47
【问题描述】:
我正在开发一个 Android 应用程序,为了让我保持登录功能,我正在使用 SharedPreferences 应用程序开始崩溃。
这是我为首选项添加的行;
SharedPreferences pref = getApplicationContext().getSharedPreferences("RS_Remember" , getApplicationContext().MODE_PRIVATE);
我很确定这条线会导致错误,因为如果我删除它就可以正常工作。
我收到的错误消息说:
java.lang.Runtime:无法创建应用程序 com.x.x.x:java.lang.NullPointerException。
知道我应该做什么吗?
编辑
public Activity activity;
SharedPreferences pref;
private RSCurrentUserManager()
{
super();
pref = this.activity.getSharedPreferences("RallySpark_Remember",0);
}
+05-09 18:02:56.221: E/AndroidRuntime(31760): FATAL EXCEPTION: main
+05-09 18:02:56.221: E/AndroidRuntime(31760):
java.lang.RuntimeException: Unable to create application
com.x.x.general.RSApplication:
java.lang.NullPointerException
+05-09 18:02:56.221:
E/AndroidRuntime(31760): at
com.x.x.general.RSCurrentUserManager.<init>(RSCurrentUserManager.java:93)
+05-09 18:02:56.221: E/AndroidRuntime(31760): at com.x.x.general.RSCurrentUserManager.getInstance(RSCurrentUserManager.java:84)
我没有在任何其他方面使用共享首选项来查找问题,我删除了除其定义之外的所有内容
【问题讨论】:
-
尝试用你的
Activity context替换getApplicationCOntext() -
getApplicationContext() 是否返回 null ?
-
不要使用
getApplicationContext(),而是使用上下文变量,你需要从你的活动中传递,context.getSharedPreferences() -
知道我应该做什么吗? 是的。您应该阅读崩溃时在日志中创建的堆栈跟踪。此跟踪将指出可能的故障点。如果之后您仍然需要帮助,请发布跟踪和相关代码。
-
我已经尝试过使用 Activit 上下文,但没有帮助。为了了解 getApplicationContext() 是否为空,我将代码替换为
if(getApplicationContext() != null) { pref = getApplicationContext().getSharedPreferences("RS_Remember" , getApplicationContext().MODE_PRIVATE); }它仍然无法正常工作
标签: android nullpointerexception sharedpreferences