我创建了一个使用SharedPreferences
的课程。在我的Activity
中,我正在尝试添加项目并收到以下错误...
06-05 17:01:53.950: E/AndroidRuntime(3488): FATAL EXCEPTION: main
06-05 17:01:53.950: E/AndroidRuntime(3488): java.lang.NullPointerException
06-05 17:01:53.950: E/AndroidRuntime(3488): at com.xcxcxc.helpers.Prefs.init(Prefs.java:16)
06-05 17:01:53.950: E/AndroidRuntime(3488): at com.xcxcxc.helpers.Prefs.addStringProperty(Prefs.java:30)
06-05 17:01:53.950: E/AndroidRuntime(3488): at com.xcxcxc.usersadapter.SplashActivity$1.callback(SplashActivity.java:78)
06-05 17:01:53.950: E/AndroidRuntime(3488): at com.xcxcxc.usersadapter.SplashActivity$1.callback(SplashActivity.java:1)
这是我处理SharedPreferences
...
import android.content.Context;
import android.content.SharedPreferences;
public class Prefs {
public static final String STORAGE_NAME = "ApplicationPrefs";
private static SharedPreferences settings = null;
private static SharedPreferences.Editor editor = null;
private static Context context = null;
public static void init(Context cntxt) {
context = cntxt;
}
private static void init() {
settings = context.getSharedPreferences(STORAGE_NAME, 0);
editor = settings.edit();
}
/* String values */
public static void addStringProperty(String name, String value) {
if (settings == null || editor == null) {
init();
}
editor.putString(name, value);
editor.commit();
}
public static String getStringProperty(String name) {
if (settings == null || editor == null) {
init();
}
return settings.getString(name, null);
}
}
这是我在Activity
...
Prefs.addStringProperty("client_id", "1JDkv9sdfj8sf63rjs");
答案 0 :(得分:0)
看起来Context是null。在addStringProperty(..)
之前设置ContextPrefs.init(getApplicationContext());
Prefs.addStringProperty("client_id", "1JDkv9sdfj8sf63rjs");
答案 1 :(得分:0)
context
似乎 null 。试着打电话
public static void init(Context cntxt)
第一
答案 2 :(得分:0)
settings = context.getSharedPreferences(STORAGE_NAME, 0);
该声明必须引起NPE
您如何以及在何处调用init(Context cntxt)
方法。
除非初始化上下文对象,否则您将获得NPE
。先修复它。
答案 3 :(得分:0)
context
可能为null,这就是你得到空指针异常的原因:
private static void init() {
settings = context.getSharedPreferences(STORAGE_NAME, 0);
editor = settings.edit();
}
首先调用public static void init(Context cntxt)
或处理空值:
private static void init() {
if(context != null){
settings = context.getSharedPreferences(STORAGE_NAME, 0);
editor = settings.edit();
}
}