我已经实现了 WebViewClient覆盖 onReceivedError()
事件。这是我的代码:
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
InternetConnectivityChecker internetConnectivityChecker = new InternetConnectivityChecker(view.getContext().getApplicationContext());
onReceivedErrorListener.onReceivedError();
if (internetConnectivityChecker.isConnected() == false) {
}
}
而且,这是我的 InternetConnectivityChecker
类:
package com.sama7.sama;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class InternetConnectivityChecker {
private Context context;
public InternetConnectivityChecker(Context context) {
context = context;
}
public boolean isConnected() {
NetworkInfo info = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
return true;
}
}
运行这段代码时,我得到一个异常,说:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at com.sama7.sama.InternetConnectivityChecker.isConnected(InternetConnectivityChecker.java:15)
为什么我的上下文是一个空对象?还有,我该如何解决这个问题?
替换:
context = context;
与:
this.context = context;
以便您设置字段的值。就目前而言,您正在为其自身设置一个方法参数。
我是一名优秀的程序员,十分优秀!