0

I need to see my location in the logs with frequency of 0.1 sec.

mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
final Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        for (int i = 1; i < 100; i++)
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    mMap.setMyLocationEnabled(true);
                    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    Criteria criteria = new Criteria();
                    final Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
                    Log.d("Coordinates: ",location.getLongitude() + "," + location.getLatitude());
                }
            }, 100 * i);

I see the coordinates in the logs with emulator, but when I connect my phone by USB, I face a crash in the line with Log.d() with the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference
Hayk Abelyan
  • 326
  • 2
  • 3
  • 19

1 Answers1

0

The last known location can be null when there's no previously recorded location found or the previous location found was from a long time ago and the gps data for it expired.

If the last location found is null, you can use fused location provider API and look for the location. You'll get it inside onLocationChanged callback.

Kushan
  • 5,855
  • 3
  • 31
  • 45
  • You'll be able to set update interval in the method used to initiate location updates... What you are doing is not going to do what you want – Kushan Mar 02 '18 at 19:20