indexoutofboundsexception index 0 size 0

2

I have a code that has to return the coordinates and the address of the coordinates of my device and the place I select on the map, the application gives me the coordinates of my rounded device, but it does not return the address, instead that's what it gives me back is an error:   "java.lang.IndexOutOfBoundsException: Index: 0 Size: 0"

But when selecting a place on the map, it returns the complete coordinates and also its address.

This is the code:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.camera_fragment, container, false);
        myplacebtn = (Button) view.findViewById(R.id.myplacebtn);//Button --get my location

        myplacebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (validatePermissionsLocation()) {
                    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
                    if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                            && ActivityCompat.checkSelfPermission(getActivity(),
                            android.Manifest.permission.ACCESS_COARSE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        return;
                    }

                    locationManager.requestLocationUpdates(
                           LocationManager.GPS_PROVIDER,
                            MINIMUM_TIME_BETWEEN_UPDATES,
                            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                            new MyLocationListener()
                    );

                        showCurrentLocation();

                }
            }
        });
//creando Mapa
   mapView = (MapView) view.findViewById(R.id.mapView);
    mapView.onCreate(savedInstanceState);

    //get a MapView
    mapView.getMapAsync(new OnMapReadyCallback() {


        @Override
        public void onMapReady(GoogleMap googleMap) {
            map = googleMap;
   //Crea Marcador en el Lugar Seleccionado en el Mapa
            // Setting a click event handler for the map
            map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

                @Override
                public void onMapClick(LatLng latLng) {

                    //Make the Address

                    getAddress(latLng);

                }
            });
            map.getUiSettings().setMyLocationButtonEnabled(false);

            LatLng jerusalem = new LatLng(32.1105435, 34.8683683);
            CameraUpdate miLocation = CameraUpdateFactory.newLatLngZoom(jerusalem, 11);
            map.moveCamera(CameraUpdateFactory.newLatLng(jerusalem));
            googleMap.animateCamera(miLocation);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(jerusalem);

           if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {


               return;
               }

                googleMap.setMyLocationEnabled(true);



            googleMap.getUiSettings().setZoomControlsEnabled(true);

        }
    });

return view;
}

 private class MyLocationListener implements LocationListener {
        public void onLocationChanged(Location location) {

        }

        public void onStatusChanged(String s, int i, Bundle b) {

        }

        public void onProviderDisabled(String s) {
           // gpsDialog();

           startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
        public void onProviderEnabled(String s) {

        }

    }

//Ubicacion de mi dispositivo
 protected void showCurrentLocation() {
        if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
                android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

           return;
        }
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);


        if (location != null) {
            //setCoordinates.setText(location.getLatitude() + " , " + 
      location.getLongitude());

            LatLng latLng=new 
      LatLng(location.getLatitude(),location.getLongitude());

            //Make Address
           getAddress(latLng);

            CameraUpdate miLocation = CameraUpdateFactory.newLatLngZoom(latLng,11);

            map.animateCamera(miLocation);

        }


    }
//Metodo que devuelve direccion y coordenadas
private void getAddress(LatLng latLng){
    Geocoder geocoder;
    List<android.location.Address> direccion = null;
    geocoder = new Geocoder(getActivity(), Locale.getDefault());
     // Creating a marker
    MarkerOptions markerOptions = new MarkerOptions();
    try {
        direccion = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // 1 representa la cantidad de resultados a obtener

        String address = direccion.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = direccion.get(0).getLocality();
        // Setting the title for the marker.
        // This will be displayed on taping the marker
        markerOptions.title(city + " : " + address);
    } catch (IOException e) {

        Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG).show();
        markerOptions.title(latLng.latitude + " , " + latLng.longitude);

    }
    catch (Exception e){

        Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG).show();
        markerOptions.title(latLng.latitude + " , " + latLng.longitude);
    }


    // Setting the position for the marker
    markerOptions.position(latLng);

    setCoordinates.setText(latLng.latitude + " , " + latLng.longitude);
    latitude = latLng.latitude;
    longitude = latLng.longitude;





    // Clears the previously touched position
    map.clear();

    // Animating to the touched position
    map.animateCamera(CameraUpdateFactory.newLatLng(latLng));

    // Placing a marker on the touched position
    map.addMarker(markerOptions);


}
    
asked by Julio Mizrahi 12.09.2018 в 09:29
source

1 answer

0

What happens is that the coordinates exist but they may not have registered address data, I recommend you validate this case.

Example:

...
...
try {
        direccion = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // 1 representa la cantidad de resultados a obtener

        if(direccion.size() > 0){

           String address = direccion.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
           String city = direccion.get(0).getLocality();
           // Setting the title for the marker.
           // This will be displayed on taping the marker
           markerOptions.title(city + " : " + address);

        }else{
           //No se encontraron datos de dirección relacionado a la geo posicion.
        }

} catch (IOException e) {

        Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_LONG).show();
        markerOptions.title(latLng.latitude + " , " + latLng.longitude);

    }

        ...
        ...
    
answered by 13.09.2018 в 04:01