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

时间:2015-11-06 23:48:04

标签: 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;

    }
}

我在我的片段中实例化了这个类

private LocationQueries locationQueries = new LocationQueries(getActivity());

但是当我尝试使用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);

2 个答案:

答案 0 :(得分:5)

您似乎在错误的地方发起了LocationQueries。的确,我认为这是:

private LocationQueries locationQueries = new LocationQueries(getActivity());

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

private class Frag extends Fragment {

    private LocationQueries locationQueries;
    ...
    @Override
    public void onCreate(Bundle inState) {
        locationQueries = new LocationQueries(getActivity());
    }
}

答案 1 :(得分:3)

您的片段似乎没有附加到活动。

我怀疑在调用onAttach(活动活动)之前,或者在片段上调用了onDetach()之后,你已经实例化了你的LocationQueries对象。

在这种情况下,调用getActivity()将返回null,然后传递给您的LocationQueries对象,从而产生NPE。

相关问题