尝试从空对象引用中读取字段“ int com.google.android.gms.location.LocationRequest.a”

时间:2018-09-08 06:02:08

标签: java android google-maps

所以我在我的活动课上遇到了称为空引用的错误 我仅在尝试将我的活动类加载到应用程序中时才收到此错误。我也收到请求的权限消息,授予权限后,出现此错误。请有人可以帮我吗?我现在要修复几个小时。

Attempt to read from field 'int com.google.android.gms.location.LocationRequest.a' on a null object reference

我不确定我哪里出错了..这是我的java类

public class Welcome extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener
{

private GoogleMap mMap;

// Play services
private static final int MY_PERMISSION_REQUEST_CODE = 7000;
private static final int PLAY_SERVICE_RES_REQUEST = 7001;

private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;

private static int UPDATE_INTERVAL = 5000;
private static int FATEST_INTERVAL = 3000;
private static int DISPLACEMENT =10;

DatabaseReference drivers;
GeoFire geoFire;

Marker mCurrent;

MaterialAnimatedSwitch location_switch;

SupportMapFragment mapFragment;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    //Initialize view

    location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
    location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(boolean isOnline) {
         if(isOnline) {
             startLocationUpdates();
             displayLocation();
             Snackbar.make(mapFragment.getView(), "You are now Online!", Snackbar.LENGTH_SHORT)
                     .show();
         }else
         {
             stopLocationUpdates();
             mCurrent.remove();
             Snackbar.make(mapFragment.getView(), "You are now Offline!", Snackbar.LENGTH_SHORT)
                     .show();
         }
        }
    });

    //Geo fire
    drivers = FirebaseDatabase.getInstance().getReference("Drivers");
    geoFire = new GeoFire(drivers);

    setUpLocation();

}


//


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode)
    {
        case MY_PERMISSION_REQUEST_CODE:
            if(grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
            {
                if(checkPlayServices()){
                    buildGoogleApiClient();
                    createLocationRequest();
                    if(location_switch.isChecked())
                        displayLocation();
                }
            }
    }
}

private void setUpLocation() {
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED  )
    {
      // Request runtime permission
        ActivityCompat.requestPermissions(this,new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
        }, MY_PERMISSION_REQUEST_CODE);

    }
    else
    {
        if(checkPlayServices()){
            buildGoogleApiClient();
            createLocationRequest();
            if(location_switch.isChecked())
                displayLocation();
        }
    }
}

private void createLocationRequest() {

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(5000);
    locationRequest.setFastestInterval(1000);
}

private void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();

    mGoogleApiClient.connect();


}

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if(resultCode != ConnectionResult.SUCCESS)
    {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
            GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICE_RES_REQUEST).show();
        else{

            Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
            finish();
        }
         return false;
    }
         return true;

}

private void stopLocationUpdates() {
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED  )
    {
        return;
    }
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,  this);
}

private void displayLocation() {
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED  )
    {
        return;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if(mLastLocation != null)
    {
        if(location_switch.isChecked())
        {
            final double latitude = mLastLocation.getLatitude();
            final double longitude = mLastLocation.getLongitude();


            //Update to firebase

            geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
                @Override
                public void onComplete(String key, DatabaseError error) {
                    //Add marker
                    if(mCurrent != null)
                        mCurrent.remove(); // remove already marker
                    mCurrent = mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.car))
                    .position(new LatLng(latitude,longitude))
                    .title("You"));

                    //Move camera to this location

                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
                    //Draw animation rotate marker
                    rotateMarker(mCurrent,-360,mMap);

                }
            });
        }
        else {
            Log.d("ERROR","Cannot get your location");
        }
    }
}

private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final float startRotation = mCurrent.getRotation();
    final long duration = 1500;

    final Interpolator interpolator = new LinearInterpolator();
    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float)elapsed/duration);
            float rot = t*i+(1-t)*startRotation;
            mCurrent.setRotation(-rot> 180?rot/2:rot);
            if(t<1.0)
            {
                handler.postDelayed(this,16);
            }

        }
    });

}

private void startLocationUpdates() {
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED  )
    {
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,  this);
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;


}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    displayLocation();
}

  //  @Override
  // public void onStatusChanged(String s, int i, Bundle bundle) {

    //}

  // @Override
  // public void onProviderEnabled(String s) {

 //  }

 // @Override
 // public void onProviderDisabled(String s) {

//}

@Override
public void onConnected(@Nullable Bundle bundle) {

    displayLocation();
    startLocationUpdates();


}

@Override
public void onConnectionSuspended(int i) {

    mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
 }

0 个答案:

没有答案