Ошибка после того, как инициализировали activity GoogleMaps

У меня есть ошибка после того, как инициализирую мою активность, где он googlemaps

ФАТАЛЬНЫЙ 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 method 'double android.location. Location.getLatitude ()' on в null object reference at android.app. ActivityThread.performLaunchActivity (ActivityThread.java:2426) at android.app. ActivityThread.handleLaunchActivity (ActivityThread.java:2490) at android.app. 900 ActivityThread.access$ (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 (Нативе Метод) 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 method 'double android.location. Location.getLatitude ()' on в 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 обитал

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);

    }
}

Меня помечает ошибка, получив длину и широту

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

Qués я врежу?

0
задан 27.01.2017, 09:06
0 ответов

Оцененный, будь должен подтверждать, location не является недействительным ли объект. Исключение происходит, когда locationManager.getLastKnownLocation (locationManager.getBestProvider (criteria, false)); возврати стоимость 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();    
                     }
2
ответ дан 03.12.2019, 17:28
  • 1
    Стой спасибо друг уже не падает aplicació n добавляя lí nea có я говорю, но мне не удается получить широту и длина я прыгает до else как ubicació n не распознанная –  27.01.2017, 19:52
  • 2
    Podrí схвати способствовать тому, чтобы твой activity осуществил LocationListener и в mé совсем '@Override public void onLocationChanged (Location location) { latitude = location.getLatitude (); длина = location.getLongitude (); }' –  27.01.2017, 20:16
  • 3
    Спасибо друг :D –  27.01.2017, 20:36