NullPointerException while getting latitude and longitude

0

I'm developing a mobile app with Android Studio that aims to get the latitude and longitude information and use the Google Geocoder service to return the address of the geographic position. However, I am not able to capture the latitude and longitude of the cell phone. What is the problem with 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;
}

Output:

  

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude ()' on a null object reference

    
asked by anonymous 15.12.2017 / 15:03

2 answers

1

Let's look at method documentation 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 GPS is disabled, location will be null and you will get NullPointerException .

This should fix your code here:

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:

  • Declaring throws Exception is a bad programming practice. Keep the set of exceptions thrown 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 buscarEndereco(double, double) method also returned null .

15.12.2017 / 15:28
2

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

The method only 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 returned Location object.

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

See this answer for the most up-to-date way to do this.

    
15.12.2017 / 15:21