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

时间:2016-03-01 13:21:20

标签: android android-context

我已实施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)

为什么我的上下文是一个空对象?而且,我该如何解决这个问题?

3 个答案:

答案 0 :(得分:5)

替换:

context = context;

使用:

this.context = context;

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

答案 1 :(得分:1)

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

谢谢

答案 2 :(得分:0)

视图有一个获取上下文的方法。查看{API} for getContext()