在Fragment中构建Google api客户端

时间:2016-06-16 09:46:13

标签: android-studio google-api-client

我在片段中构建google api客户端时遇到错误。我得到的错误是;

   java.lang.ClassCastException: net.janusjanus.we4x4_v1.upload cannot be cast to com.google.android.gms.common.api.GoogleApiClient$OnConnectionFailedListener

我已实施GoogleApiClient.ConnectionCallbacksGoogleApiClient.OnConnectionFailedListenerLocationListener

并请求构建如下;

         mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) getActivity())
            .addApi(LocationServices.API)
            .build();

首先我在声明新的GoogleApiClient.Builder时遇到了问题,我将其声明为;

          mGoogleApiClient = new GoogleApiClient.Builder(this)

作为错误加下划线,因此我必须尝试多种方式来声明它,getActivity()getContext()。但我得到了同样的错误?

对于我在这里做错了什么以及正确的方法有什么想法?

2 个答案:

答案 0 :(得分:1)

在我的情况下,我必须声明GoogleApiClient.Builder如下;

 mGoogleApiClient = new GoogleApiClient.Builder(UploadPictures.this.getContext())

其中UploadPictures是片段名称。

希望这对某人有帮助。

答案 1 :(得分:0)

实施GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener和LocationListener

        @Override
        public void onConnectionFailed(ConnectionResult result) {
        }

        @Override
        public void onConnected(Bundle arg0) {
        }

        @Override
        public void onConnectionSuspended(int arg0) {
        }

        @Override
        public void onLocationChanged(Location location) {
        }

然后将代码更改为:

mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();