我正在尝试显示我的当前位置,但是我遇到了这个问题。我不知道哪一部分是错误,我放入Common.mLastLocation和ACCESS_COARSE_LOCATION。请问你能帮帮我吗。我的位置返回NULL,最近我更改了库“ com.google.android.gms:play-services-maps:11.8.0”。我的logcat是:尝试调用虚拟方法'double android.location.Location.getLatitude()

第一部分:

public class Home_rider extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener ,
        OnMapReadyCallback{

    SupportMapFragment mapFragment;

    FusedLocationProviderClient fusedLocationProviderClient;
    LocationCallback locationCallback;

    //Location
    private GoogleMap mMap;
    private static final int MY_PERMISSION_REQUEST_CODE = 7192; // MY Birthday
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 300193; // MY CODE

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

    private static int UPDATE_INTERVAL = 5000; // 5 secs
    private static int FATEST_INTERVAL = 3000;
    private static int DISPLACEMENT = 10;

    DatabaseReference ref;
    GeoFire geoFire;

    Marker mUserMarker,markerDestination;

    boolean isDriverFound=false;
    String driverId="";
    int radius = 1; //1km
    int distance = 1; //3km
    private static final int LIMIT = 3;

    //BottomSheet
    ImageView imgExpandable;
    BottomSheetRiderFragment mBottomSheet;
    Button btnPickupRequest;

    //Presense system
    DatabaseReference driversAvailable;

    //Send Alert
    IFCMService mService;

    PlaceAutocompleteFragment place_location,place_destination;

    String mPlaceLocation,mPlaceDestination;

    //New Update Information
    CircleImageView imageAvatar;
    TextView txtRiderName,txtStars;

    //Declare FireStorage to upload avatar
    FirebaseStorage storage;
    StorageReference storageReference;

Get location:

private void setUpLocation() {
        //Copy code from Driver APP
        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
        {

                buildLocationCallBack();
                createLocationRequest();
                displayLocation();
        }

    }

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;
        }

        fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                Common.mLastLocation = location;
                if (Common.mLastLocation != null)
                {


                    //Create LatLng from mLastLocation and this is center point
                    LatLng center = new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude());
                    //Distance in meters
                    //Heading 0 is northside , 90 is east, 180 is south and 270 is west
                    //Base compat
                    LatLng northSide = SphericalUtil.computeOffset(center,100000,0);
                    LatLng southSide = SphericalUtil.computeOffset(center,100000,180);

                    LatLngBounds bounds = LatLngBounds.builder()
                            .include(northSide)
                            .include(southSide)
                            .build();

                    place_location.setBoundsBias(bounds);

                    place_destination.setBoundsBias(bounds);

                    //Presense System
                    driversAvailable = FirebaseDatabase.getInstance().getReference(Common.driver_tbl);
                    driversAvailable.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            //If have any change from Drivers table , we will reload all drivers available
                            loadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude()));
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                    final double latitude = Common.mLastLocation.getLatitude();
                    final double longitude = Common.mLastLocation.getLongitude();



                    loadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude()));


                    Log.d("MoaguiTaxi",String.format("No se pudo encontrar su ubicación : %f / %f", latitude, longitude));
                }
                else
                {
                    Log.d("MoaguiTaxi","No se pudo encontrar su ubicación");
                }
            }
        });

    }


private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

@Override
    public void onMapReady(GoogleMap googleMap) {

        try {
            boolean isSucces = googleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(this,R.raw.my_map_style)
            );

            if (!isSucces)
                Log.e("ERROR","No se cargó el mapa");
        }
        catch (Resources.NotFoundException ex)
        {
            ex.printStackTrace();
        }


        mMap = googleMap;
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(true);
        mMap.setInfoWindowAdapter(new CustomInfoWindow(this));

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                //First , check markerDestination
                //If is not null , just remove available marker
                if (markerDestination != null)
                    markerDestination.remove();
                markerDestination = mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker))
                .position(latLng)
                .title("Destination"));
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15.0f));

                //Show bottom sheet
                BottomSheetRiderFragment mBottomSheet = BottomSheetRiderFragment.newInstance(String.format("%f,%f",mLastLocation.getLatitude(),mLastLocation.getLongitude()),
                        String.format("%f,%f",latLng.latitude,latLng.longitude)
                        ,true);

                mBottomSheet.show(getSupportFragmentManager(),mBottomSheet.getTag());
            }
        });

        //Copy code from Driver APP
        if (ActivityCompat.checkSelfPermission(Home_rider.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(Home_rider.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        buildLocationCallBack();
        fusedLocationProviderClient.requestLocationUpdates(mLocationRequest,locationCallback, Looper.myLooper());
    }


}

最佳答案

这是因为您在mLastLocation.getLatitude()中使用的是Common.mLastLocation.getLatitude()而不是setOnMapClickListener

错误基本上是在空引用上调用getLatitude()

08-25 01:38