尝试在空对象引用上调用虚拟方法 'double android.location.Location.getLatitude()'

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

我创建了 Maps Directions 应用程序,我设法将我的位置打开到目的地位置并单击 GO 按钮,应用程序然后强制关闭,

我在尝试对空对象调用双精度虚方法 android.location.Location.getLatitude() 时遇到 NullPointerException。

package com.kelompok8.kontakservicekonser;

<LIST IMPORT>

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

private GoogleMap mMap;

//Play Servis

        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;

        //Animasi
        private List<LatLng> polyLineList;
        private Marker teknisiMarker;
        private float v;
        private double lat, lng;
        private Handler handler;
        private LatLng startPosition, endPosition, currentPosition;
        private int index, next;
        private Button btnGo;
        private EditText edtPlace;
        private String destination;
        private PolylineOptions polylineOptions,blackPolylineOptions;
        private Polyline blackPolyLine, greyPolyline;

        private IGoogleAPI mService;

        Runnable drawPathRunnable=new Runnable() {
            @Override
            public void run() {
                if (index<polyLineList.size()-1)
                {
                    index++;
                    next = index;
                }
                if (index < polyLineList.size()-1)
                {
                    startPosition = polyLineList.get(index);
                    endPosition = polyLineList.get(next);

                }

                ValueAnimator valueAnimator = ValueAnimator.ofFloat(0,1);
                valueAnimator.setDuration(3000);
                valueAnimator.setInterpolator(new LinearInterpolator());
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                        v = valueAnimator.getAnimatedFraction();
                        lng = v*endPosition.longitude+(1-v)*startPosition.longitude;
                        lat = v*endPosition.latitude+(1-v)*startPosition.latitude;
                        LatLng newPos = new LatLng(lat,lng);
                        teknisiMarker.setPosition(newPos);
                        teknisiMarker.setAnchor(0.5f,0.5f);
                        teknisiMarker.setRotation(getBearing(startPosition,newPos));
                        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(
                                new CameraPosition.Builder()
                                .target(newPos)
                                .zoom(15.5f)
                                .build()

                                ));
                    }
                });
                valueAnimator.start();
                handler.postDelayed(this,3000);

            }
        };

        private float getBearing(LatLng startPosition, LatLng endPosition) {
            double lat = Math.abs(startPosition.latitude - endPosition.latitude);
            double lng = Math.abs(startPosition.longitude - endPosition.longitude);

            if (startPosition.latitude < endPosition.latitude && startPosition.longitude < endPosition.longitude)
                return (float)(Math.toDegrees(Math.atan(lng/lat)));

            else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude < endPosition.longitude)
                return (float)((90-Math.toDegrees(Math.atan(lng/lat)))+90);
            else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude >= endPosition.longitude)
                return (float)(Math.toDegrees(Math.atan(lng/lat))+180);
            else if (startPosition.latitude < endPosition.latitude && startPosition.longitude >= endPosition.longitude)
                return (float)((90-Math.toDegrees(Math.atan(lng/lat)))+270);

            return -1;
        }


        @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);

    //Init 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 Online",Snackbar.LENGTH_SHORT)
                        .show();
            }
            else
            {
                stopLocationUpdates();
                mCurrent.remove();
                mMap.clear();
                handler.removeCallbacks(drawPathRunnable);
                Snackbar.make(mapFragment.getView(),"You Are Offline",Snackbar.LENGTH_SHORT)
                        .show();

            }

        }
    });

    polyLineList = new ArrayList<>();
    btnGo = (Button) findViewById(R.id.btnGo);
    edtPlace = (EditText) findViewById(R.id.edtPlace);

    btnGo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            destination = edtPlace.getText().toString();
            destination = destination.replace(" ","+"); //Replace spasi dengan + untuk Fecth data
            Log.d("KELOMPOK8", destination);

            getDirection();
        }
    });

    //Geo Fire

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

    setUpLocation();

    mService = Common.getGoogleAPI();



}

        private void getDirection() {
            currentPosition = new LatLng (mLastLocation.getLatitude(), mLastLocation.getLongitude());


            String requestApi = null;
            try{
                requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+
                        "mode=driving&"+
                        "transit_routing_preference=less_driving"+
                        "origin="+currentPosition.latitude+","+currentPosition.longitude+"&"+
                        "destination="+destination+"&"+
                        "key="+getResources().getString(R.string.google_direction_api);

                Log.d("KELOMPOK8",requestApi); //Print URL
                mService.getPath(requestApi)
                        .enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response.body().toString());
                                    JSONArray jsonArray = jsonObject.getJSONArray("routes");
                                    for (int i=0;i<jsonArray.length();i++)
                                    {
                                        JSONObject route = jsonArray.getJSONObject(i);
                                        JSONObject poly = route.getJSONObject("overview_polyline");
                                        String polyline = poly.getString("points");
                                        polyLineList = decodePoly(polyline);
                                    }

                                    //Ajusting Bounds

                                    LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                    for (LatLng latLng:polyLineList)
                                        builder.include(latLng);
                                    LatLngBounds bounds = builder.build();
                                    CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds,2);
                                    mMap.animateCamera(mCameraUpdate);

                                    polylineOptions = new PolylineOptions();
                                    polylineOptions.color(Color.GRAY);
                                    polylineOptions.width(5);
                                    polylineOptions.startCap(new SquareCap());
                                    polylineOptions.endCap(new SquareCap());
                                    polylineOptions.jointType(JointType.ROUND);
                                    polylineOptions.addAll(polyLineList);
                                    greyPolyline = mMap.addPolyline(polylineOptions);

                                    blackPolylineOptions = new PolylineOptions();
                                    blackPolylineOptions.color(Color.BLACK);
                                    blackPolylineOptions.width(5);
                                    blackPolylineOptions.startCap(new SquareCap());
                                    blackPolylineOptions.endCap(new SquareCap());
                                    blackPolylineOptions.jointType(JointType.ROUND);
                                    blackPolyLine = mMap.addPolyline(blackPolylineOptions);

                                    mMap.addMarker(new MarkerOptions()
                                            .position(polyLineList.get(polyLineList.size()-1))
                                                .title("Pick Up Location"));

                                    //Animation

                                    ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0,100);
                                    polyLineAnimator.setDuration(2000);
                                    polyLineAnimator.setInterpolator(new LinearInterpolator());
                                    polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                        @Override
                                        public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                            List<LatLng> points = greyPolyline.getPoints();
                                            int percentValue = (int)valueAnimator.getAnimatedValue();
                                            int size = points.size();
                                            int newPoints = (int)(size *(percentValue/100.0f));
                                            List<LatLng> p = points.subList(0,newPoints);
                                            blackPolyLine.setPoints(p);
                                        }
                                    });
                                    polyLineAnimator.start();
                                    teknisiMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
                                    .flat(true)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));

                                    handler = new Handler();
                                    index=-1;
                                    next=1;
                                    handler.postDelayed(drawPathRunnable,3000);




                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {
                                Toast.makeText(Welcome.this,""+t.getMessage(),Toast.LENGTH_SHORT).show();

                            }
                        });

            }catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        private List decodePoly(String encoded) {

            List poly = new ArrayList();
            int index = 0, len = encoded.length();
            int lat = 0, lng = 0;

            while (index < len) {
                int b, shift = 0, result = 0;
                do {
                    b = encoded.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lat += dlat;

                shift = 0;
                result = 0;
                do {
                    b = encoded.charAt(index++) - 63;
                    result |= (b & 0x1f) << shift;
                    shift += 5;
                } while (b >= 0x20);
                int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
                lng += dlng;

                LatLng p = new LatLng((((double) lat / 1E5)),
                        (((double) lng / 1E5)));
                poly.add(p);
            }

            return poly;
        }

        @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() {
                mLocationRequest= new LocationRequest();
                mLocationRequest.setInterval(UPDATE_INTERVAL);
                mLocationRequest.setFastestInterval(FATEST_INTERVAL);
                mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
        }

        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, "Device ini tidak Cocok", 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();

                        geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
                            @Override
                            public void onComplete(String key, DatabaseError error) {
                                if ((mCurrent) !=null)
                                    mCurrent.remove();
                                mCurrent = mMap.addMarker(new MarkerOptions()
                                                            .position(new LatLng(latitude, longitude))
                                                            .title("Your Location"));
                                //Memindah Kamera ke Posisi kita

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

                            }



                        });

                    }
                }
            }
            else
            {
                Log.d("ERROR","Tidak bisa mengambil Lokasi");
            }

        }

        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 elepsed = SystemClock.uptimeMillis() - start;
                    float t = interpolator.getInterpolation((float)elepsed/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;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mMap.setTrafficEnabled(false);
    mMap.setIndoorEnabled(false);
    mMap.setBuildingsEnabled(false);
    mMap.getUiSettings().setZoomControlsEnabled(true);



}

        @Override
         public void onConnected(@Nullable Bundle bundle) {
            displayLocation();
            startLocationUpdates();

        }

        @Override
        public void onConnectionSuspended(int i) {
            mGoogleApiClient.connect();

        }

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

        }

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

        }
    }

异常原因

private void getDirection() {
            currentPosition = new LatLng (mLastLocation.getLatitude(), mLastLocation.getLongitude());


            String requestApi = null;
            try{
                requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+
                        "mode=driving&"+
                        "transit_routing_preference=less_driving"+
                        "origin="+currentPosition.latitude+","+currentPosition.longitude+"&"+
                        "destination="+destination+"&"+
                        "key="+getResources().getString(R.string.google_direction_api);

                Log.d("KELOMPOK8",requestApi); //Print URL
                mService.getPath(requestApi)
                        .enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response.body().toString());
                                    JSONArray jsonArray = jsonObject.getJSONArray("routes");
                                    for (int i=0;i<jsonArray.length();i++)
                                    {
                                        JSONObject route = jsonArray.getJSONObject(i);
                                        JSONObject poly = route.getJSONObject("overview_polyline");
                                        String polyline = poly.getString("points");
                                        polyLineList = decodePoly(polyline);

列表导入

您忘记初始化 Location,只需添加:

LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();

String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);

onCreate() 方法:

之后从位置获取纬度和经度:

double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng latLng = new LatLng(lat, lng);

编码愉快!!