-5

我正在为 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)

谁能给我一些关于我应该如何解决这个问题的线索?

4

2 回答 2

1

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

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

connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
于 2013-04-28T17:33:40.530 回答
0

始终将这种类型的方法创建为实用程序方法。

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;
    }
于 2013-04-28T17:35:15.330 回答