我正在为 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)
谁能给我一些关于我应该如何解决这个问题的线索?