我有一个活动显示一些列表条目.当我点击列表项目时,我的应用程序通过NetworkInfo.getTypeName()检查可用的连接类型(“WIF”或“MOBILE”).一旦我调用这个方法,我得到一个NullpointerException.为什么?
我在模拟器上测试了这个,因为我的手机目前不可用(坏了…).我假设这是问题?这是我唯一的解释,如果不是这样,我不知道为什么这将是null.
以下是一些代码段:
public class VideoList extends ListActivity{ ... public void onCreate(Bundle bundle){ final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); ... listview.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> parent,View view,int position,long id) { ... NetworkInfo ni = cm.getActiveNetworkInfo(); String connex = ni.getTypeName(); //Nullpointer exception here if(connex.equals("WIFI")doSomething(); } }); } }
解决方法
如果没有活动网络,则调用getActiveNetworkInfo()可以返回null,并且需要检查.这是
here的源代码.
/** * Return NetworkInfo for the active (i.e.,connected) network interface. * It is assumed that at most one network is active at a time. If more * than one is active,it is indeterminate which will be returned. * @return the info for the active network,or {@code null} if none is active */ public NetworkInfo getActiveNetworkInfo() { enforceAccessPermission(); for (NetworkStateTracker t : mNetTrackers) { NetworkInfo info = t.getNetworkInfo(); if (info.isConnected()) { return info; } } return null; }
特别注意javadoc:“返回活动网络的信息,如果没有活动,则返回null”.