java - 问题: Attempt to invoke virtual method 'double android. location.Location.getLatitude()

标签 java

我正在尝试显示我当前的位置,但遇到了这个问题。我不知道错误在哪一部分,我把 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());
    }


}

最佳答案

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

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

关于java - 问题: Attempt to invoke virtual method 'double android. location.Location.getLatitude(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56555288/

相关文章:

java - Vertx 在 html 中使用上传的图像

java - 这个类是POJO吗

java - 为什么要为抽象类或接口(interface)类烦恼呢?

java - Java中的弹跳球

java - Android异步任务的同步策略

java - 获取Java泛型的类,以及泛型的接口(interface)实现

java - 我的新游戏按钮和退出游戏按钮不起作用

java - 支持复制选项

java - 安全地保留数据

java - Dynamo DB 中的自动递增计数器