Android Helper class -> null pointer exception

2019-08-16 23:45发布

问题:

i would like to ask:

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?

Thanks for any advice.

回答1:

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.

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.