我有 5 个选项卡的选项卡活动,在其中一个选项卡中,我试图检测互联网连接并在有互联网连接时进行一些活动。我使用的代码是
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
Toast.makeText(ApplicationManagement.tabcontext, "Data Uploading to the Server", Toast.LENGTH_LONG).show();
} else {
// Internet connection is not present
// Ask user to connect to Internet
Toast.makeText(ApplicationManagement.tabcontext, "Please check your internet connection and TRY AGAIN", Toast.LENGTH_LONG).show();
}
}
});
我在行获得 NullPointerExceptionisInternetPresent = cd.isConnectingToInternet();
ConnectionDetector.java 是:
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
我似乎无法弄清楚为什么会出现空指针异常???是因为我使用标签是因为标签会产生很多上下文问题吗???请帮忙!