Error getting user's location - Android GPS

2

I am new to the development of applications for Android and I am creating an application which makes use of the user's location. The problem is that sometimes I get a Lat and Long of (0,0). I mean, he can not read it. But this only happens with certain devices, which do not follow any pattern in common.

I really do not know the problem and I think it may be because the system can not get these coordinates when the application asks for them.

The code I use to get the user's location is the following:

 private Location getMyLocation() {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location myLocation;
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(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.

    }
    myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);


    try
    {
        //El if es para que nos deje de mostrar el "checkpermission", y nos deje obtener la localizacion
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {

            if (myLocation == null)
            {
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_COARSE);
                String provider = lm.getBestProvider(criteria, true);
                myLocation = lm.getLastKnownLocation(provider);
            }


        }
        else
        {
            if (myLocation == null)
            {
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_COARSE);
                String provider = lm.getBestProvider(criteria, true);
                myLocation = lm.getLastKnownLocation(provider);
            }
        }

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

    }


    return myLocation;

}

The error that marks me is the following:

  

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

    
asked by Alan Oliver 21.03.2018 в 07:19
source

2 answers

2

When the location manager is not able to return a location at that moment, you can place a listener so that each time lapse or a certain distance is updated and you return a location. In this example, the distance is 0 and the time is 0, so you will try to return the location immediately.

You need to implement LocationListener or place it in requestLocationUpdates

Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null){
    //haz lo que necesites con tu ubicacion
} else{
   mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}

.......

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        Log.v(TAG, location.getLatitude() + " " + location.getLongitude());
        //en el if de arriba no fue capaz de regresar la ubicacion, asi que entro al listener y aca ya es una ubicacion valida
        mLocationManager.removeUpdates(this); //para remover el listener y solo escuchar el cambio de ubicacion 1 vez           
    }
}

// metodos requeridos por el LocationListener
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

To add the LocationListener you have 2 options, one, make implements in your activity or fragment or where you need to use it. You will notice that the IDE if you use android studio at least, it will indicate in red that there is an error, you can press ALT + Enter and you will get a window like this, which tells you the methods that you should implement (which are the ones that are below)

public class MiActivity extends AppCompatActivity implements LocationListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {}  
    //etc etc tus metodos y lo demas

    //aca es donde te va a pedir que sobre escribas los metodos
    @Override
    public void onLocationChanged(Location location) {}
    // metodos requeridos por el LocationListener
    public void onProviderDisabled(String arg0) {}
    public void onProviderEnabled(String arg0) {}
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}

The other option is to use it directly in the location manager

mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,new LocationListener(){
        @Override
        public void onLocationChanged(Location location) {
            //aca es donde validas que la ubicacion sea valida, etc 
        }
        //los 3 metodos que se sobre escriben al usar el locationListener
        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {}
        @Override
        public void onProviderEnabled(String s) {}
        @Override
        public void onProviderDisabled(String s) {}
    });
    
answered by 21.03.2018 / 16:25
source
0

The problem indicates that you are trying to call getLatitude() in an instance of Location with null value:

  

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

The problem occurs because the provider you use is not available, you must activate it.

I suggest you validate only get the values of latitude and longitude if the value of the instance Location is different to null:

if(myLocation != null) {

    //Obtener valores
}

I also see that you added the block to validate if you have the permission but you are not requiring it, therefore myLocation would have a null value, you must add the permission request within this block:

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

This would show the dialog to accept the required permissions for Android 6.0 or higher devices

this would be the code:

private Location getMyLocation() {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location myLocation;
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(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.



      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 120); //*** Agrega la petición!

    }
    myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
...
...
    
answered by 21.03.2018 в 17:27