1

我有 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;
}
}

我似乎无法弄清楚为什么会出现空指针异常???是因为我使用标签是因为标签会产生很多上下文问题吗???请帮忙!

4

3 回答 3

1

您忘记cd初始化ConnectionDetector. 像调用 isConnectingToInternet() 方法之前一样初始化它:

cd=new ConnectionDetector(Your_Current_Activity.this);
isInternetPresent = cd.isConnectingToInternet();
于 2013-05-27T09:09:36.037 回答
0

是的,您获得了 NPE,因为您忘记创建一个新的ConnectionDetector. 使用该代码再试一次:

ConnectionDetector cd = new ConnectionDetector(this);
于 2013-05-27T09:09:50.337 回答
0

使用这种方式创建 ConnectionDetector 对象然后使用

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
 ConnectionDetector cd=new ConnectionDetector(this);
        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();




} 
于 2013-05-27T09:10:17.210 回答