在确定当前位置时捕获Android异常

时间:2018-02-13 17:19:40

标签: android google-maps

打开MapFragment时,相机会动画到给定位置: Initial position

当我点击导航按钮(右上角)时,它会动画到我当前的位置: enter image description here

在处理第一个动画时单击导航按钮时发生异常。

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

根据代码,在连接GoogleApiClient之前必须禁用该按钮,但是,无论如何它似乎都已启用。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

    mMountainItems = MountainsUtils.get().getMountainItems();

    getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            updateUI();
        }
    });

    mClient = new GoogleApiClient.Builder(getActivity())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle bundle) {
                    setCurrentLocation();
                    getActivity().invalidateOptionsMenu();
                }
                @Override
                public void onConnectionSuspended(int i) {
                }
            })
            .build();
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.fragment_allmountains, menu);

    MenuItem searchItem = menu.findItem(R.id.action_locate);
    searchItem.setEnabled(mClient.isConnected());
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_locate:
            if(mClient.isConnected()){
                if (hasLocationPermission()) {
                    findCurrentLocation();
                }else {
                    requestPermissions(LOCATION_PERMISSIONS,
                            REQUEST_LOCATION_PERMISSIONS);
                }
            }else{
                Snackbar.make(getView(), "Location is not identified yet", Snackbar.LENGTH_SHORT).show();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void findCurrentLocation(){
    if (mMap == null) {
        return;
    }

    LatLng myPoint = new LatLng(
            mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
    LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
    boundsBuilder.include(myPoint);
    MarkerOptions myMarker = new MarkerOptions()
            .position(myPoint);
    mMap.addMarker(myMarker);
    animateCamera(boundsBuilder);

}

@SuppressLint("MissingPermission")
public void setCurrentLocation(){
    LocationRequest request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    request.setNumUpdates(1);
    request.setInterval(0);

    LocationServices.FusedLocationApi
            .requestLocationUpdates(mClient, request, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    mCurrentLocation = location;
                    Log.d(TAG, mCurrentLocation.getLatitude() + " : " + mCurrentLocation.getLongitude());
                }
            });
}`enter code here`

fragment_allmountains.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto">
        <item android:id="@+id/action_locate"
              android:icon="@android:drawable/ic_menu_compass"
              android:title="@string/search"
              android:enabled="false"
              app:showAsAction="ifRoom"/>
    </menu>

可以找到整个片段代码here 任何帮助,将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

您应该在setCurrentLocation()内拨打findCurrentLocation()并致电

LatLng myPoint = new LatLng( mCurrentLocation.getLatitude(), 
 mCurrentLocation.getLongitude()); 
LatLngBounds.Builder boundsBuilder = 
 new LatLngBounds.Builder(); boundsBuilder.include(myPoint); 
 MarkerOptions myMarker = new MarkerOptions() .position(myPoint); 
 mMap.addMarker(myMarker); 
animateCamera(boundsBuilder);

内部      onLocationChanged