将上下文从活动内的片段传递到另一个类

Bog*_*iel 0 java android android-fragments android-studio

我有一个由Activity实例化的片段.我遇到的问题是我在片段中有另一个类,它将一个参数作为一个Activity上下文.

public class LocationQueries {
    Activity context;

    private static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 200;

    public LocationQueries(Activity context) {
        this.context = context;
    }

    public boolean checkGooglePlayServices() {

        int checkGooglePlayServices = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(context);
        if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
              /*
               * google play services is missing or update is required
               *  return code could be
               * SUCCESS,
               * SERVICE_MISSING, SERVICE_VERSION_UPDATE_REQUIRED,
               * SERVICE_DISABLED, SERVICE_INVALID.
               */
            GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices,
                    context, REQUEST_CODE_RECOVER_PLAY_SERVICES).show();

            return false;
        }

        return true;

    }
}
Run Code Online (Sandbox Code Playgroud)

我像这样在我的片段中实例化该类

private LocationQueries locationQueries = new LocationQueries(getActivity());
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用时 locationQueries.checkGooglePlayServices();

我得到Caused by: java.lang.NullPointerException: Attempt to invoke virtual method android.content.pm.PackageManager android.content.Context.getPackageManager() on a null object reference.看起来它LocationQueries(getActivity())实际上没有传递活动上下文.我怎么解决这个问题?

编辑:如果我从一个活动 - >做同样的事情,一切正常 LocationQueries(this);

fll*_*llo 5

看来你LocationQueries是在错误的地方发起的.的确,我认为这个:

private LocationQueries locationQueries = new LocationQueries(getActivity());
Run Code Online (Sandbox Code Playgroud)

在您的Fragment类中被称为全局变量.
相反,您应该将变量保持为全局变量,但将其设置为onCreate()或onResume(),如下所示:

private class Frag extends Fragment {

    private LocationQueries locationQueries;
    ...
    @Override
    public void onCreate(Bundle inState) {
        locationQueries = new LocationQueries(getActivity());
    }
}
Run Code Online (Sandbox Code Playgroud)