0

Tengo un error al iniciar mi actividad en donde está googlemaps

FATAL EXCEPTION: main Process: com.appmovilperote, PID: 9854 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appmovilperote/com.appmovilperote.GoogleMaps.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) at android.app.ActivityThread.access$900(ActivityThread.java:154) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5443) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference at com.appmovilperote.GoogleMaps.MapsActivity.onCreate(MapsActivity.java:90) at android.app.Activity.performCreate(Activity.java:6259) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) ... 9 more

MapsActivity.java

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, DirectionFinderListener {

    private GoogleMap mMap;
    private List<Marker> originMarkers = new ArrayList<>();
    private List<Marker> destinationMarkers = new ArrayList<>();
    private List<Polyline> polylinePaths = new ArrayList<>();
    private ProgressDialog progressDialog;
    private ImageView imvruta;

    public static String nombre;
    public static double lat, lng;
    public static LatLng destin;
    public static LatLng orign;
    double  latitude;
    double longitud;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);




        Bundle extras = getIntent().getExtras();
        lat = extras.getDouble("LATITUD");
        lng = extras.getDouble("LONGITUD");
        nombre = extras.getString("NOMBRENEGOCIO");

        destin = new LatLng(lat, lng);

        imvruta = (ImageView)findViewById(R.id.imv_type_ruta);

        LocationManager locationManager = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        //A API 17
        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        latitude = location.getLatitude();
        longitud = location.getLongitude();

        orign = new LatLng(latitude,longitud);

    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        CameraPosition cameraPosition = CameraPosition.builder()
                .zoom(17).target(destin).build();

        mMap.addMarker(new MarkerOptions().position(destin).title(nombre)).showInfoWindow();
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mMap.setMyLocationEnabled(true);

    }
}

Me marca error al obtener la longitud y latitud

 latitude = location.getLatitude();
 longitud = location.getLongitude();

¿Qués estoy haciendo mal?

2
  • 1
    Lo principal que estas haciendo mal esta tener una excepción y no compartirla entera. La Excepción básicamente te pega con un palo en la cabeza diciéndote donde queda tu error. compártelo, y lo veremos. el 27 ene. 2017 a las 6:47
  • Métete en tu IDE y búsca línea 90 en com.appmovilperote.GoogleMaps.MapsActivity (debe ser en onCreate(Bundle ...) el 27 ene. 2017 a las 6:59

1 respuesta 1

2

Estimado, debe confirmar si el objeto location no es nulo. La excepción ocurre cuando locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); devuelve un valor null.

    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
                   if(location != null){ 
                       latitude = location.getLatitude();
                       longitud = location.getLongitude();

                       orign = new LatLng(latitude,longitud);

                     }  else  {
                       Toast.makeText(getContext(), "Última ubicación no reconocida", Toast.LENGTH_SHORT).show();    
                     }
3
  • Vale gracias amigo ya no se cae la aplicación agregando la línea de código, pero no logro obtener la latitud y longitud me brinca hasta el else como ubicación no reconocida el 27 ene. 2017 a las 17:52
  • Podrías hacer que tu activity implemente LocationListener y en el método ` @Override public void onLocationChanged(Location location) {latitude = location.getLatitude(); longitud = location.getLongitude();} `
    – Diego
    el 27 ene. 2017 a las 18:16
  • Gracias amigo :D el 27 ene. 2017 a las 18:36

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.