Catch latitude Android - Location == null

Asked

Viewed 5,690 times

3

I’m having trouble getting latitude and longitude on Android. Using this function, always the "Location" returns "null".

public void onCreate() {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        la = location.getLatitude();
        lo = location.getLongitude();
        Log.d("create", "la = " + la + " e lo = " + lo);
        new Thread(localizacao.this).start();
    } else {
        Log.d("update", "location null");
    }
}

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Can you help me?

3 answers

4

You can’t pick up the location so directly, take a look at the documentation: http://developer.android.com/training/location/retrieve-current.html

The moment you are trying to get the location, the device still does not have to provide you, which causes Nullpointer.

I suggest taking a look at the documentation to see how you can implement a Locationlistener, where within it you can check if you have a location to be returned, get location update using the onLocationChanged method and checking changes in the status of the Provider.

An implementation below:

public class Localizacao implements LocationListener {

    protected static final String TAG = null;
    private Context context;
    private LocationManager lm;
    private Location location;
    private volatile boolean stop = false;
    private static final int UM_SEGUNDO = 1000;
    private int tempoTotalBusca = 10;
    protected ProgressDialog progressDialog;

    public Localizacao(Context context) {
        lm = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        this.context = context;
    }

    public boolean estado() {
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public Location capturarCoordenadaGPS() {

        try {
            new Thread(new Runnable() {
                public void run() {
                    Looper.myLooper();
                    Looper.prepare();

                    progressDialog = ProgressDialog.show(context, null,
                            context.getString(R.string.aguarde),
                            true);

                    ativaGPS();
                    Looper.loop();
                }
            }).start();
            // Thread.sleep(10*1000);

            int tempoBusca = 0;

            while (!stop) {
                if (tempoTotalBusca == tempoBusca) {
                    break;
                }

                Thread.sleep(UM_SEGUNDO);
                tempoBusca++;
            }
            return location;
        } catch (Exception e) {
            // TODO - Trate a exceção;
        } finally {
            desativaGPS();
            if (progressDialog != null)
                progressDialog.dismiss();
        }
        return null;
    }

    private void ativaGPS() {
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this,
                Looper.myLooper());
        // Looper.loop();
    }

    private void desativaGPS() {
        lm.removeUpdates(Localizacion.this);
    }

    @Override
    public void onLocationChanged(Location location) {
        this.location = location;
        stop = true;
    }

    @Override
    public void onProviderDisabled(String provider) {
        // Provider desabilitado
    }

    @Override
    public void onProviderEnabled(String provider) {
        // Provider habilitado
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // Status do provider alterado
    }

}
  • Could you give some more relevant information here? "replies" only with link tend to become invalid over time if there is any change.

  • Lucas, I tried to use the class you posted, but I keep getting NULL. <pre><code>public void onCreate() { Locates = new Locates(getApplicationContext()); Location = locates.capturrCoordenadaGPS(); if (Location != null) { la = Location.getLatitude(); lo = Location.getLongitude(); Log. d("create", "la = " + la + " and lo = " + lo); } Else { Log. d("update", "Location null"); } }</code></pre> Any suggestions?

  • You need to wait for a location to be available, place a breakpoint within the onLocationChanged method, and simulate a change of location using Eclipse Locationcontrols.

  • I used the eclipse location change and tested on the mobile. Unsuccessful...

  • Matheus, try the following test: put a breakpoint inside the onLocationChanged method and then simulate location by Eclipse, everything is correct the execution will fall at breakpoint.

  • Lucas, I put the breakpoint and it’s falling right, but the Location is NULL.

  • Fixing Lucas, on onLocationChanged Location is correct with LA/LO, but the return is NULL.

  • Well, if it’s correct, just take the property Location. In it will be the coordinates you want. In fact, the onLocationChanged method is void, returns nothing, just arrow the updated Location. So, just access this property.

  • Is there any way to call onLocationChanged without actually changing the location? PQ can only get the Location on onLocationChanged can’t get the capture.

  • Matheus, you must use the getLastKnowLocation() method. LocationManager locationMngr = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); &#xA;&#xA;Location localizacao = locationMngr .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // Aqui o parametro é o seu provider, pode ser NETWORK_PROVIDER ou GPS_PROVIDER.

Show 5 more comments

1


When you start the location service, it will only return you a valid position after it has managed to discover the user’s location. Try the following:

public class MainActivity extends FragmentActivity implements GooglePlayServicesClient.ConnectionCallbacks,    
                                                        GooglePlayServicesClient.OnConnectionFailedListener
{
    private LocationClient locationClient;
    private Location currentLocation = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //Inicializa o objeto e registra os callbacks.
        locationClient = new LocationClient(this, this, this);
    }

    @Override
    protected void onStart(){
        super.onStart();

        //Tentamos nos conectar ao serviço de localização.
        locationClient.connect();
    }

    @Override
    protected void onStop(){
       //Disconectamos do serviço de localização quando o app sai do foco.
       locationClient.disconnect();
       super.onStop();
    }


    @Override
    public void onConnected(Bundle bundle) {
        //Estamos devidamente conectados ao serviço de localização.
        //Podemos pegar posições a vontade agora.
        //Se você quiser, pode usar uma variavel booleana aqui,
        //para dizer ao seu app que ele pode pegar posições de localização
        //diferentes de null.
        currentLocation = locationClient.getLastLocation();
    }

    @Override
    public void onDisconnected() {
        //Aqui você pode alterar a variável booleana para seu app não tentar
        //pegar mais posições de localização, embora, caso você tenha se
        //conectado ao serviço, e você tente pegar uma localização,
        //ele irá retornar a última localização disponível.
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //O Google Play consegue resolver alguns problemas de conexão com
        //sistema de localização. Aqui a gente verificar se o Google Play
        //tem a solução para o erro que ocorre.
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);              
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } 

    }

}

Just remember that this code uses the Googleplayservices library.

In this code we implement interfaces that are listeners to the state of the device location system. Thus, we can know when the localization system will return us a valid location.

1

Wow, I’m having exactly the same problem, I’ve tried everything with Googleplayservices, direct using a Listener in the onLocationChanged method, and nothing, I get a result that is Location other than null. On some devices like a Samsung S2 works perfectly.

// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled && !isNetworkEnabled) {
    if (location == null) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
        Log.d(Const.TAG, "GPS ENABLED (LocationTracker.java)");
        if (locationManager != null) {
            // even this line it does not work
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

            // this line always returns null, no matter what I do
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.