context.getSharedPreferences(string name,int mode) 空指针异常

本文探讨了在Android开发中使用SharedPreferences时遇到的空指针异常问题,并详细解释了异常出现的原因及如何避免该问题的发生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值