public SharedPreferenceUtils(Context context,String name) {
LogUtil.i("Test",context.toString());
mSharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
}
工具类里获取ShardPreferences对象时报错:java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.fuyong.smartbutler/com.fuyong.smartbutler.ui.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
04-23 16:07:50.212 189com.fuyong.smartbutler I/Test: com.fuyong.smartbutler.ui.LoginActivity@999a96a
尝试Log打印context确认context对象已经传进来,按理不会空指针。
报错时我是在Activity的成员变量位置调用这个工具类的构造方法:
private SharedPreferenceUtils mSpUser = mSpUser = new SharedPreferenceUtils(this, FILE_USER);
当我试着把它放到onCreate方法里之后Bug解决,原因是在成员变量位置传入“this"时,Activity还未构建出来自然不能当作上下文使用
mSpUser = new SharedPreferenceUtils(this, FILE_USER);