Android Helper类->空指针异常 [英] Android Helper class -> null pointer exception
问题描述
我想问:
在我的AppHelper类中,有以下方法可以检查互联网连接的可用性.
I have in my AppHelper class following method which check availability of internet connection.
public boolean checkInternetConnection(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
Log.i(GlobalApplication.APP_LOG_NAMESPACE, "Internet Connection Not Present");
return false;
}
}
我正在尝试通过以下方式获取布尔值:
Im trying to get Boolean value by using:
// check internet connection and availability
Boolean isConnectionAvailable = appHelper.checkInternetConnection(getBaseContext());
但是不幸的是,我总是得到空指针异常.传递的应用程序上下文有关系吗?我该如何解决这个问题?
But unfortunately i get always null pointer exception. Is it matter of passed application context? And how should i solve that issue?
谢谢您的任何建议.
推荐答案
我要在黑暗中a一口,说AppHelper类是一个单独的Activity,永远不会从意图上正确启动.
I'm going to take a stab in the dark and say that AppHelper class is a seperate Activity that is never properly started with an intent.
如果是这样,我会改为将AppHelper作为服务而不是Activity来实现,因为"checkInternetConnection"方法更适合此类任务.
If this is so, I would instead implement AppHelper as a Service instead of an Activity, as the method "checkInternetConnection" is better suited for this type of task.
该服务是否在其自身的进程中运行或不运行,取决于我眼前的具体问题.
Weather or not the service runs in its own process or not I suppose would depend on the particular problem at hand.
这篇关于Android Helper类->空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!