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.