Nullpointerexception error when obtaining location

Asked

Viewed 57 times

1

I’m making an app that shows user coordinates:

This works properly and checks if the 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 calling the pegaCoord 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 mistake 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

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 right or should I do different?

Can you help me? Hugs.

2 answers

3

Location é null.

This is not going to work:

longitude = location.getLongitude();

Where is this variable location?

I believe this is:

location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

If this is the case it would not be better to pass this variable as 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();
  • I changed how I spoke and gave the same mistake :/

  • where I include => Location Location = new Location();

  • I could not start the variables the way you gave me. he asked for some parameters in Location(...) and others. as I’m still a beginner, I couldn’t make it work. Anyway, thanks for the help.

  • Well, that means you need a few things to start using Location. I don’t know if it’s the same command on the other Ides but on Eclipse if you put Location location = new Location(); and press F3 on top of new "Location()" it will take you to the class constructor and so you can see what kind of parameter it waits to be started.

  • I’m using Android Studio

  • Maybe it’s interesting then to take a look at this website, do not know if you already know all shortcuts. And the equivalent of F3 in this case appears to be Ctrl+alt+b

  • still do not know, I’m programming for android a few days. thanks for the tip

Show 2 more comments

3


It occurs because the object Location is null.

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

There is a more current way of picking up the location than the locationManager.

Follow an example:

Add the following dependency on the project’s Gradle:

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

His 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 to your AndroidManifest:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  • I was able to solve with the method that Voce passed me. now how do I know if the device has GPS and inform the user if there is no?

  • Similarly! See onConnected method! It’s the same q there is in your verified methodGps

  • only one more to end rsrs: in the tests I did, the app runs without asking the user permission to use the location. how do I inform (or open a screen), requesting permission to use the GPS?

  • Get a look at this link! http://stackoverflow.com/questions/29801368/how-to-show-enable-location-dialog-likegoogle-maps

Browser other questions tagged

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