Nullpointerexception when obtaining latitude and longitude

Asked

Viewed 182 times

0

I am developing a mobile application with Android Studio that aims to get the information of latitude and longitude and use the service of Google Geocoder to return the address of the geographical position. However, I am not able to capture the latitude and longitude of the cell phone. What is the problem of my code?

public class MainActivity extends AppCompatActivity {

private Location location;
private LocationManager locationManager;
private Address endereco;

double longitude = 0.0;
double latitude = 0.0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_denuncia );

    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        // Check Permissions Now
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
        return;
    }else{
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }

        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.i( "Longitude", String.valueOf( location.getLongitude() ) );

    try {
        endereco = buscarEndereco(latitude, longitude);
        EditText editText = (EditText)findViewById(R.id.bairro);
        editText.setText(endereco.getLocality(), TextView.BufferType.EDITABLE);
    }catch (IOException e){
        Log.i("GPS", e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public Address buscarEndereco(double latitude, double longitude)throws Exception{
    Geocoder geocoder;
    Address address = null;
    List<Address> addresses;
    geocoder = new Geocoder(getApplicationContext());
    addresses = geocoder.getFromLocation(latitude, longitude, 1);
    if(addresses.size() > 0){
        address = addresses.get(0);
    }
    return address;
}

Exit:

java.lang.Nullpointerexception: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null Object Reference

2 answers

2

The method getLastKnownLocation() can return null. This is more likely if you are using an emulator.

The method just does not return null if any application has ever requested the location of the device. Of course you must also have "Location" enabled on the device.

You can avoid the error by testing whether the location is null or not before using the object Location returned.

Of course this only solves part of the problem. To ensure that your application gets a valid location you have to request it.

Look at this reply the most current (date) way of doing so.

1


Let’s see the documentation of the method LocationManager.getLastKnownLocation(String):

If the Provider is Currently disabled, null is returned.

Translating:

If the provider is disabled, null is returned.

Let’s see your code:

location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

latitude = location.getLatitude();

That is, when the GPS is disabled, location will be null and you’ll get the NullPointerException.

This here should fix your code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_denuncia);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
            return;
        }

        EditText editText = (EditText) findViewById(R.id.bairro);

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location == null) {
            editText.setText("GPS desativado.");
            return;
        }

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        Log.i("Longitude", String.valueOf(location.getLongitude()));

        try {
            Address endereco = buscarEndereco(latitude, longitude);
            String local = endereco == null ? null : endereco.getLocality();
            editText.setText(local == null ? "???" : local, TextView.BufferType.EDITABLE);
        } catch (IOException e) {
            Log.i("GPS", e.getMessage());
        }
    }

    private Address buscarEndereco(double latitude, double longitude) throws IOException {
        Geocoder geocoder = new Geocoder(getApplicationContext());
        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        return addresses.isEmpty() ? null : addresses.get(0);
    }
}

Other details to take into account:

  • Declare throws Exception is bad programming practice. Keep the set of released exceptions as specific and as generic as possible.

  • Avoid using instance attributes to do what can be solved with local variables.

  • Another NullPointerException could occur if the method buscarEndereco(double, double) also return null.

  • I’m suspicious with some kind of permission. Even with the GPS active it shows the GPS message disabled. Then I opened the apk google maps and returned to my application, then he managed to return to geolocation. However if I disable the gps, close the maps, activate the gps again and enter my application informs gps disabled. What could be?

  • 1

    @Carlosdiego. I don’t know, but that would be something for another question. The problem of this one was the NullPointerException. If/when creating another question about this, I recommend putting the complete and compileable code in it, and clearly describing the steps needed to reproduce the problem.

  • Okay, I’m going to analyze here, if by chance I can’t open a new question. But it worked partially.

  • 1

    @Carlosdiego Having GPS enabled is not enough for that method getLastKnownLocation() return a value. To verify that the problem is the one that I indicate in my reply use the Google application and get your location, then run your.

Browser other questions tagged

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