Catch latitude longitude Android - Location == null

3

I'm having trouble catching latitude and longitude on Android. Using this function, the "location" always 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?

    
asked by anonymous 30.01.2014 / 19:08

3 answers

1

When you start the location service, it will only return you a valid position once it has been able to figure out 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 remembering that this code uses the GooglePlayServices library.

In this code we implement interfaces that are listeners for the state of the device's localization system. So we can tell when the location system will return a valid location.

    
31.01.2014 / 03:55
4

You can not get the location directly, take a look at the documentation: link

At the moment you are trying to get the location, the device does not have it yet, which is NullPointer.

I suggest you read through the documentation to see how you can implement a LocationListener, where you can check if it has a location to be returned, get location update using the onLocationChanged method, and check for changes in provider status.

One 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
    }

}
    
30.01.2014 / 19:12
1

Hello, I have exactly the same problem, I have tried everything with GooglePlayServices, direct using a Listener in the onLocationChanged method, and nothing, nothing I can 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();
            }
        }
    }
}
    
29.03.2014 / 15:02