NullPointerException error getting location

1

I'm making an application that shows the user's coordinates:

This works correctly and checks to see if GPS is released:

public void verificaGPS(){
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //GPS desligado ou sem permissão
        txtLatitude.setText("sem GPS");
    }else{
        //GPS OK
        txtLatitude.setText("com GPS");
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        pegaCoord();
    }
}

It works until you call the handleCoord () function:

public void pegaCoord() {
    longitude = location.getLongitude();
    latitude = location.getLatitude();

    txtLatitude.setText("Latitude: " + latitude);
    txtLongitude.setText("Longitude: " + longitude);

    try {
        txtCidade.setText("Cidade: " + buscarEndereco(latitude, longitude).getLocality());
        txtEstado.setText("Estado: " + buscarEndereco(latitude, longitude).getAdminArea());
        txtPais.setText("País: " + buscarEndereco(latitude, longitude).getCountryName());
        txtHora.setText("Sol nasce às: " + String.valueOf(horaSol(latitude,longitude)));
    } catch (IOException e) {
        Log.i("GPS", e.getMessage());
    }
}

The error is:

    07-28 17:47:39.497 20924-20924/br.com.wiconsultoria.tattwas E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.wiconsultoria.tattwas, PID: 20924
java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.wiconsultoria.tattwas/br.com.wiconsultoria.tattwas.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference

I created the variable at the top before starting the code.

public class MainActivity extends AppCompatActivity {
    public Location location;
    public LocationManager locationManager;
    public double latitude;
    public double longitude;

Is it right or should I do something different?

Can you help me? Hugs.

    
asked by anonymous 28.07.2016 / 23:01

2 answers

3

Occurs because the object Location is null .

When it tries to access the variable location.getLongitude() , it bursts the error!

There is a more current way to get location than locationManager .

Here's an example:

Add the following dependency in the project gradle:

dependencies {
.....
compile 'com.google.android.gms:play-services-location:9.2.0'
}

Your Activity:

 public class SuaActivity extends AppCompatActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

        private GoogleApiClient mGoogleApiClient;
        /**
         * Instacia o GoogleApiClient para obter a localização!
         */
        private void startLocationService(){
            mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext()).
                    addApi(LocationServices.API).
                    addOnConnectionFailedListener(this).
                    addConnectionCallbacks(this).
                    build();
            mGoogleApiClient.connect();
        }

        /**
         * Método é chamado quando o GoogleApiClient se connecta!
         */
        @Override
        public void onConnected(@Nullable Bundle bundle) {
            final LocationRequest request = LocationRequest.create();
            request.setInterval(500); // Intervalo de Atualizações
            request.setPriority(100); //Prioridade
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, this);
        }
        /**
         * Método invocado quando a conexão é suspensa!
         */
        @Override
        public void onConnectionSuspended(int i) {
        }

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

        @Override
        protected void onStop() {
            super.onStop();
            if(null != mGoogleApiClient){
                mGoogleApiClient.disconnect();
            }
        }

        /**
         * Método é chamado toda vez que recebe uma nova Localização!
         * Definido pelo (request.setInterval())
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            if(null == location){
                return;
            }


            //Aqui você deve chamar seu método pegaCoord();

        }

        /**
         * Invocado quando ocorre um erro ao se conectar!
         */
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult 

connectionResult) {
    }
}

Remember that you need to add the following permissions on your AndroidManifest :

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
28.07.2016 / 23:18
3

Location is null.

Because of this this will not work:

longitude = location.getLongitude();

Where is this variable location ?

I think it's this:

location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

If this is the case, would not it be better to pass this variable as a parameter?

location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
pegaCoord(location);


public void pegaCoord(Location location) {
   longitude = location.getLongitude();
   latitude = location.getLatitude();
   // codigo
}

I also noticed that Location was not started. You have to remember to start the variables:

public class MainActivity extends AppCompatActivity {
public Location location = new Location();
public LocationManager locationManager = new LocationManager();
public double latitude = new Double();
public double longitude = new Double();
    
28.07.2016 / 23:04