2017-04-09 97 views
0

我收到提示我的片段類,這是狀態Android的一個空對象引用

的Java -boolean com.google.android.gms.common.api.GoogleApiClient.isConnected()」。 lang.NullPointerException:嘗試在fragment.HomeFragment.onResume

上的空對象引用調用虛擬方法「布爾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. LocationListener的
  5. DirectionFinderListener

有人可以幫助我?

+0

的可能的複製[什麼是空指針異常,如何修復它(http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-做-I-FIX-IT)。我們只需要兩個相關的代碼部分:您從未向我們展示過您將「mGoogleApiAgent」分配到哪裏。 –

+0

@ M.Prokhorov我編輯了我的文章。 – nao

+0

考慮到你添加的部分,我的鏈接甚至比它更相關。 –

回答

0

您需要保留對您正在構建的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(); 
} 
+0

它是在私人同步無效buildGoogleApiClient()? – nao

+0

是的。如果只調用'onCreate'中的'buildGoogleApiClient()'方法,你甚至不需要使用synchronized。它總是會被主線程調用,所以沒有同步問題 – quiro

+0

我做了,但現在我得到錯誤聲明>必須調用addApi()添加至少一個API – nao