在类中获取NULL指针异常以检查Internet

时间:2011-12-16 05:42:05

标签: android multithreading exception nullpointerexception

我正在创建一个类来检查互联网连接,我收到以下错误:

 12-16 10:34:07.340: E/AndroidRuntime(1099):
  

java.lang.NullPointerException 12-16 10:34:07.340:   E / AndroidRuntime(1099):at   com.internetchecker.main.InternetCheckerActivity $ 1.onClick(InternetCheckerActivity.java:25)   12-16 10:34:07.340:E / AndroidRuntime(1099):at   android.view.View.performClick(View.java:2485)12-16 10:34:07.340:   E / AndroidRuntime(1099):at   android.view.View $ PerformClick.run(View.java:9080)12-16 10:34:07.340:   E / AndroidRuntime(1099):at   android.os.Handler.handleCallback(Handler.java:587)12-16   10:34:07.340:E / AndroidRuntime(1099):at   android.os.Handler.dispatchMessage(Handler.java:92)12-16   10:34:07.340:E / AndroidRuntime(1099):at   android.os.Looper.loop(Looper.java:123)12-16 10:34:07.340:   E / AndroidRuntime(1099):at   android.app.ActivityThread.main(ActivityThread.java:3683)12-16   10:34:07.340:E / AndroidRuntime(1099):at   java.lang.reflect.Method.invokeNative(Native Method)12-16   10:34:07.340:E / AndroidRuntime(1099):at   java.lang.reflect.Method.invoke(Method.java:507)12-16 10:34:07.340:   E / AndroidRuntime(1099):at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839)   12-16 10:34:07.340:E / AndroidRuntime(1099):at   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)12-16   10:34:07.340:E / AndroidRuntime(1099):at   dalvik.system.NativeStart.main(原生方法)

我班级的代码如下:

public class CheckInternet2 {
private static Boolean status =  true;
public static Boolean isConnected() {
    Runnable runnable = new Runnable() {
        public void run() {
            // TODO Auto-generated method stub
            isNetworkAvailable(h,2000);             
        }           
    };
    runnable.run();
    return status;
}
private static Handler h = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        if (msg.what != 1) { // code if not connected
            status = false;
            System.out.println("Status False");
        } else { // code if connected
            status = true;
            System.out.println("Status True");
        }
    }
};

private static  void isNetworkAvailable(final Handler handler, final int timeout) {

    new Thread() {

        private boolean responded = false;
        @Override
        public void run() {

            new Thread() {
                @Override
                public void run() {
                    HttpGet requestForTest = new HttpGet("http://m.google.com");
                    try {
                        new DefaultHttpClient().execute(requestForTest); // can last...
                        responded = true;
                    } catch (Exception e) {}
                }
            }.start();
            try {
                int waited = 0;
                while(!responded && (waited < timeout)) {
                    sleep(100);
                    if(!responded ) { 
                        waited += 100;
                    }
                }
            } 
            catch(InterruptedException e) {} // do nothing 
            finally { 
                if (!responded) { handler.sendEmptyMessage(0);
                } 
                else { handler.sendEmptyMessage(1); 
                }
            }
        }
    }.start();
}
}

我将其称为:

btnCheckStatus.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if(CheckInternet2.isConnected())
                {
                    Toast.makeText(getApplicationContext(), "Connected ", 0).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Not Connected ", 0).show();
                }


            }
        });

我无法弄清楚为什么抛出异常。

2 个答案:

答案 0 :(得分:2)

检查网络可用性以及wifi状态

检查网络可用性

public static boolean isNetworkPresent(Context context) {
        boolean isNetworkAvailable = false;
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        try {

            if (cm != null) {
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null) {
                    isNetworkAvailable = netInfo.isConnectedOrConnecting();
                }
            }
        } catch (Exception ex) {
            Log.e("Network Avail Error", ex.getMessage());
        }
        //check for wifi also
        if(!isNetworkAvailable){
            WifiManager connec = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            State wifi = cm.getNetworkInfo(1).getState();
            if (connec.isWifiEnabled()
                    && wifi.toString().equalsIgnoreCase("CONNECTED")) {
                isNetworkAvailable = true;
            } else {

                isNetworkAvailable = false;
            }

        }
        return isNetworkAvailable;
    }

答案 1 :(得分:0)

这在我的代码中运行良好:

    public boolean isOnline(Context cxt) {

    try{

        ConnectivityManager conMan = (ConnectivityManager)cxt.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conMan.getActiveNetworkInfo();
        Log.d(Log_Tag,networkInfo.getState().toString());
        if(networkInfo.isConnected()){
          Log.d(Log_Tag,networkInfo.toString());
            return true;
        } 
        else {
            return false;
        }
    }
    catch(Exception ex)
    {
        Log.i(Log_Tag, "isOnline ERROR: "+ex.toString());
        return false;
    }

}

我尝试了你在问题中所写的内容。我显示了一些错误。所以我用过它。