如何从视图中获取上下文?

How can I get context from a view?

我已经实现了 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 class:

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;

以便您设置字段的值。就目前而言,您正在为其自身设置一个方法参数。

视图有一个获取上下文的方法。请参阅 android API 以获得 getContext()

要获取应用程序的上下文,您可以使用 getApplicationContext。这将为您提供您正在处理的应用程序的上下文。

谢谢