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