use*_*494 10 networking android nullpointerexception
我有一个显示一些List条目的活动.当我点击列表项时,我的应用程序通过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();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 10
getActiveNetworkInfo()如果没有活动网络,则调用可以返回null,您需要检查该调用.下面是从源代码在这里.
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
请特别注意javadoc:"返回活动网络的信息,如果没有活动网络则返回null".
| 归档时间: |
|
| 查看次数: |
5835 次 |
| 最近记录: |