【问题标题】:NullPointerException on getSystemService() when checking network connectivity [closed]检查网络连接时 getSystemService() 上的 NullPointerException [关闭]
【发布时间】:2020-04-19 23:22:48
【问题描述】:

当我在一个片段中检查与 Internet 的连接时,我收到错误 NullPointerException,但在另一个片段中它工作得非常好。

public static boolean isOnline() {
    ConnectivityManager connectivityManager = (ConnectivityManager)
            Injection.provideZiauddinAppInstance()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

【问题讨论】:

  • 显然provideZiauddinAppInstance() 为空
  • 显然,您使用的上下文已死。 provideZiauddinAppInstance() 返回什么,哪个上下文?
  • 它与其他片段一起工作正常它是从注入类返回的 mvp 结构如果使用上下文从应用程序类获取上下文它会在 getsystemService() 上给出错误(不能从静态上下文引用非静态方法)此外getApplicationContext 没有选项。
  • 你有没有调试过你得到空指针异常的确切时间?

标签: android android-fragments nullpointerexception


【解决方案1】:

创建一个 ConnectivityReceiver 类:

public class ConnectivityReceiver {

    public static boolean isNetworkConnected(Activity activity) {

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

        return cm.getActiveNetworkInfo() != null;
    }
}

然后在任何你想要的地方使用 Like this :

if (ConnectivityReceiver.isNetworkConnected(this)) {
//do your things
}

【讨论】:

  • 这绝对对我有用
  • 那么请为答案投票,以便其他人也可以找到他们想要的答案
  • 如何完成答案? stackoverflow 已经阻止了我提出问题的限制。
  • 完成答案??你这是什么意思?
  • 我怎样才能将这个问题锁定为一个完整的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 2021-09-29
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
相关资源
最近更新 更多