Я не получаю адрес моего местоположения (java.lang.IndexOutOfBoundsException: Index: 0 Size: 0) - PullRequest
0 голосов
/ 12 сентября 2018

У меня есть код, который должен возвращать координаты и адрес координат моего устройства и место, которое я выбираю на карте, приложение выдает мне округленные координаты моего устройства, но оно не возвращает адрес, вместо этого мне возвращается ошибка:

java.lang.IndexOutOfBoundsException: индекс: 0 размер: 0

Но при выборе места на карте он возвращает полные координаты, а также свой адрес.

Это код:

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

                }
            }
        });
//create the map
   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 marker when i select a place in the map
            // 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) {

        }

    }

//Location of my device
 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);

        }


    }
//Method return the coordinates and the address
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);


}

Ответы [ 2 ]

0 голосов
/ 12 сентября 2018

Очевидно, что ваша проблема связана с этим методом:

//Method return the coordinates and the address
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);


}

здесь, этот блок

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

        String address = direccion.get(0).getAddressLine(0); // crash happens here
        String city = direccion.get(0).getLocality();
        // Setting the title for the marker.
        // This will be displayed on taping the marker
        markerOptions.title(city + " : " + address);
    }

выходит из строя, потому что для некоторых устройств старый подход (выше одного) к reverse geocoding больше не работает (по крайней мере, для некоторых устройств он возвращается пустым) .

Итак, вам придется конвертировать адрес из Geocoding API.

васможете проверить как отсюда: Ссылка для обратного геокода

0 голосов
/ 12 сентября 2018

Прежде чем получить доступ к данным из списка, сначала проверьте, пусто ли оно или нет

...