【Android踩坑记】SharedPreferences 出现空指针异常

1.我希望通过使用SharedPreferences及SharedPreferences.Editor来存储一些轻量级的数据,比如用户的登录信息,游戏得分,然后一开始我是这样写的:
  

SharedPreferences preferences = getActivity().getSharedPreferences("Bublurl",0);

然后出现了如下问题:Attempt to invoke virtual method on a null object reference for SharedPreferences in ActionbarActivity's Fragment
--即出现了空指针的异常。
然后我将代码改动如下:

public String getBulbsUrl() {
SharedPreferences preferences = mContext.getSharedPreferences("Bublurl",0); String url = preferences.getString("url","http://");
return url;
}

结果可以正常使用。
--下面是stackOverFlow上的解答为什么会出现空指针的异常
--另外,在构建类的时候最好使用一个属性:private Context mcontext;
http://stackoverflow.com/questions/27614361/attempt-to-invoke-virtual-method-on-a-null-object-reference-for-sharedpreference/35027177#35027177

你可能感兴趣的:(【Android踩坑记】SharedPreferences 出现空指针异常)