【问题标题】:Android -boolean com.google.android.gms.common.api.GoogleApiClient.isConnected()' on a null object referenceAndroid -boolean com.google.android.gms.common.api.GoogleApiClient.isConnected()' 在空对象引用上
【发布时间】:2017-04-09 13:26:26
【问题描述】:

我的片段类出现错误

java.lang.NullPointerException:尝试在 fragment.HomeFragment.onResume 的空对象引用上调用虚拟方法“boolean com.google.android.gms.common.api.GoogleApiClient.isConnected()”

这是我在 HomeFragment 上的部分代码

private GoogleApiClient mGoogleApiClient;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION);
        mCameraPosition = 
savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
    }        buildGoogleApiClient();
}

@Override
public void onResume() {
    super.onResume();
    if (mGoogleApiClient.isConnected()) {
        getDeviceLocation();
    }
    updateMarkers();
}

    private synchronized void buildGoogleApiClient() {
    GoogleApiClient.Builder builder = new GoogleApiClient.Builder(getActivity());
    mGoogleApiClient = builder.build();
    //builder.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */);
    builder.addConnectionCallbacks(this);
    builder.addApi(LocationServices.API);
    builder.addApi(Places.GEO_DATA_API);
    builder.addApi(Places.PLACE_DETECTION_API);
    builder.build();
    createLocationRequest();
}

我也实现了

  1. OnMapReadyCallback
  2. GoogleApiClient.ConnectionCallbacks
  3. GoogleApiClient.OnConnectionFailedListener
  4. 位置监听器
  5. DirectionFinderListener

有人可以帮我解决这个问题吗?

【问题讨论】:

  • What is NullPointerException and how do I fix it 的可能重复项。我们需要的两个代码中只有一个相关的代码部分:你从来没有告诉我们你在哪里分配了mGoogleApiAgent
  • @M.Prokhorov 我编辑了我的帖子。
  • 考虑到您添加的部分,我的链接比以前更相关。

标签: java android google-maps android-fragments


【解决方案1】:

您需要保留对您正在构建的GoogleApiClient 实例的引用。所以应该是:

private void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
        .addConnectionCallbacks(this)
        .addApi(LocationServices.API)
        .addApi(Places.GEO_DATA_API)
        .addApi(Places.PLACE_DETECTION_API)
        .build();
    createLocationRequest();
}

【讨论】:

  • 是否在私有同步 void buildGoogleApiClient() 上?
  • 是的。此外,如果您只在onCreate 中调用buildGoogleApiClient() 方法,您甚至不需要使用同步。它总是会被主线程调用,所以没有同步问题
  • 我这样做了,但现在我收到错误声明 > 必须调用 addApi() 来添加至少一个 API
  • @nao,那么您应该添加至少一个 Api - 异常消息通常至少有些帮助。
  • @nao 我用正确的方式编辑了我的答案以构建GoogleApiClient
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 2017-07-16
  • 1970-01-01
  • 2015-08-21
  • 2021-05-04
  • 2016-06-12
相关资源
最近更新 更多