奇怪的nullpointer异常错误

时间:2013-04-28 17:27:19

标签: java android

我正在为Android开发应用,我是应用开发的新手。在这个应用程序中,我正在检查按钮单击上的互联网连接并在日志缓冲区中输出结果但我得到一个强制关闭与networkcheck boolean上的nullpointerexception

我的代码是

public class Loginpage extends Activity {

private Context context;
private static String TAG = "DH";
private ConnectivityManager connManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loginpage);
    Button button = (Button) findViewById(R.id.login);

    button.setOnClickListener(new OnClickListener()
    {
      public void onClick(View v)
      {
          if(networkisOk())
        {
                Log.e(TAG, "We have Internet!");
        }
        else
        {
            Log.e(TAG, "We don't have Internet!");
        }
      }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.loginpage, menu);
    return true;
}

public final boolean networkisOk()
{
    connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo info = connManager.getActiveNetworkInfo();
    if (info != null)
        return info.isConnected(); // WIFI connected
    else
        return false;
}

}

使用调试器时,该行Nullpointer异常的断点显示在行

connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

错误显示为

04-28 22:46:21.259: E/AndroidRuntime(26936): java.lang.NullPointerException
04-28 22:46:21.259: E/AndroidRuntime(26936):at  com.varun.dev_host.Loginpage.networkisOk(Loginpage.java:52)

有人能为我提供一些解决方法吗?

2 个答案:

答案 0 :(得分:1)

您似乎忘记了初始化context成员

ActivityContext的子类,因此您无需声明/初始化要使用的单独Context。而只是做;

connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

答案 1 :(得分:0)

始终将此类方法创建为Utility方法。

public static boolean isNetworkAvailable(Context ctx) {
        boolean connected = false;

        ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm != null) {
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();

            for (NetworkInfo ni : netInfo) {
                if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni.getTypeName().equalsIgnoreCase("MOBILE"))
                        && ni.isConnected()) {
                    connected = true;
                }
            }
        }
        return connected;
    }