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

1.我希望通过使用SharedPreferences及SharedPreferences.Editor来存储一些轻量级的数据,比如用户的登录信息,游戏得分,然后一开始我是这样写的:
  <pre><code>SharedPreferences preferences = getActivity().getSharedPreferences("Bublurl",0);</code></pre>
然后出现了如下问题:Attempt to invoke virtual method on a null object reference for SharedPreferences in ActionbarActivity's Fragment
--即出现了空指针的异常。
然后我将代码改动如下:
<code>
public String getBulbsUrl() {
SharedPreferences preferences = mContext.getSharedPreferences("Bublurl",0); String url = preferences.getString("url","http://");
return url;
}</code>
结果可以正常使用。
--下面是stackOverFlow上的解答为什么会出现空指针的异常
--另外,在构建类的时候最好使用一个属性:private Context mcontext;
http://stackoverflow.com/questions/27614361/attempt-to-invoke-virtual-method-on-a-null-object-reference-for-sharedpreference/35027177#35027177

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容