0

I know that there are already several answers to this problem, but unfortunately I'm a beginner and I can not find the right solution for this problem. The getLastKnowPosition method returns me nothing. How can I solve this? I would need the current position of the device.

EDITED I'm now trying the solution posted in the comment.

CODE

public class IntellySearch extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private LocationManager locationManager;
private double posLat;
private double posLng;
private LatLng position;
private Marker mPosition;
private int numero = 1;
private FusedLocationProviderClient mFusedLocationClient;

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

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if (location != null){
                posLat = location.getLatitude();
                posLng = location.getLongitude();
            }
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d("IntActivity", "Error getting last GPS location");
            e.printStackTrace();
        }
    });



    startGPS();
}


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

    // Add a marker in Sydney and move the camera
    LatLng duomo = new LatLng(43.773251, 11.255474);

    //mMap.moveCamera(CameraUpdateFactory.newLatLng(duomo));
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(duomo, 18f));
}


public void startGPS() {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 5);
    }


    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            posLat = location.getLatitude();
            posLng = location.getLongitude();

            position = new LatLng(posLat, posLng);

            if (mPosition != null) {
                mPosition.remove();
            }

            mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position"));
            if (numero < 2) {
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 18));
                numero = 30;
            }
            mMap.moveCamera(CameraUpdateFactory.newLatLng(position));

        }

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

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    });

}

The stacktrace refers to two line of code:

FIRST

public void onLocationChanged(Location location) {
            posLat = location.getLatitude();
            posLng = location.getLongitude();

            position = new LatLng(posLat, posLng);

            if (mPosition != null) {
                mPosition.remove();
            }

SECOND

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

    // Add a marker in Sydney and move the camera
    LatLng duomo = new LatLng(43.773251, 11.255474);

    //mMap.moveCamera(CameraUpdateFactory.newLatLng(duomo));
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(duomo, 18f));
}

STACKTRACE

2019-01-31 11:10:30.269 7441-7441/com.icloud.andreadimartino.bellini I/Google Maps Android API: Google Play services client version: 12211000
2019-01-31 11:10:30.275 7441-7441/com.icloud.andreadimartino.bellini I/Google Maps Android API: Google Play services package version: 13280022
2019-01-31 11:10:30.311 1368-1411/? W/audio_hw_generic: Hardware backing HAL too slow, could only write 0 of 720 frames
2019-01-31 11:10:30.463 7441-7441/com.icloud.andreadimartino.bellini E/art: The String#value field is not present on Android versions >= 6.0
2019-01-31 11:10:30.896 7441-7441/com.icloud.andreadimartino.bellini E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.icloud.andreadimartino.bellini, PID: 7441
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.icloud.andreadimartino.bellini/com.icloud.andreadimartino.bellini.IntellySearch}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.LocationManager.requestLocationUpdates(java.lang.String, long, float, android.location.LocationListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.LocationManager.requestLocationUpdates(java.lang.String, long, float, android.location.LocationListener)' on a null object reference
        at com.icloud.andreadimartino.bellini.IntellySearch.startGPS(IntellySearch.java:104)
        at com.icloud.andreadimartino.bellini.IntellySearch.onCreate(IntellySearch.java:79)
        at android.app.Activity.performCreate(Activity.java:6662)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)

How i solve it?

  • Possible duplicate of [getLastKnownLocation returns null](https://stackoverflow.com/questions/20438627/getlastknownlocation-returns-null), specifically [Binesh Kumar's answer](https://stackoverflow.com/a/48033659/469080) – Michael Dodd Jan 31 '19 at 09:44
  • In short, from the code you've posted it looks like you're using the old API. The answer I've linked to shows you how to use the newer API – Michael Dodd Jan 31 '19 at 09:46
  • @MichaelDodd I'll try with the newer API – Andrea Di Martino Jan 31 '19 at 09:51
  • It doesn't matter which API you use. If the device doesn't know its location it can't tell you its location. And an up-to-date location isn't automatically maintained. Sometimes it may be available if some other app has requested location updates. You need to request location updates yourself to make sure that you get an up-to-date location. – Markus Kauppinen Jan 31 '19 at 09:58
  • And actually the answer linked above doesn't help either as is explained in its comment by Selvin. – Markus Kauppinen Jan 31 '19 at 10:01
  • Possible duplicate of [Error invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference](https://stackoverflow.com/questions/32290045/error-invoke-virtual-method-double-android-location-location-getlatitude-on) – Markus Kauppinen Jan 31 '19 at 10:02
  • @MichaelDodd i have always a null object. I'm going to edit my answer. – Andrea Di Martino Jan 31 '19 at 10:03
  • @MarkusKauppinen That's why I specifically linked to Binesh's answer, not the accepted answer. The accepted answer is similar if not identical to OP's code. – Michael Dodd Jan 31 '19 at 10:05
  • I know that the last location can be null, but how i can get the current location? The real current location i mean – Andrea Di Martino Jan 31 '19 at 10:15
  • 1
    Android documentation on `FusedLocationProviderClient.getLastLocation()` as used in the linked answer by Binesh Kumar: _"Returns the best most recent location currently available. If a location is not available, which should happen very rarely, null will be returned."_ So, it's not the solution for situations where the device does not know its location. Requesting location updates is. And it doesn't happen "rarely" when people are developing apps and not running other apps in the background and are testing indoors without a SIM card when both GPS and network based locations are unavailable. – Markus Kauppinen Jan 31 '19 at 10:34
  • @MarkusKauppinen so i just make a request update location for one time and i get the current device position. – Andrea Di Martino Jan 31 '19 at 10:50

0 Answers0