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
网友评论