简体   繁体   中英

geocoder.getFromLocationName error

Getting "always true" result on if (location != null || !location.equals("")) and when I search something like "sldjfuhsdhfj" it closes the app, but when I enter something like "Central Park" it works correctly. What am I doing wrong? Code I am using

public void onMapSearch(View view) {
    EditText locationSearch = (EditText) findViewById(R.id.editText1);
    String location = locationSearch.getText().toString();
    List<Address> addressList = null;

    if (location != null || !location.equals("")) {
        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location, 1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Do something after 3s
                mMap.clear();
            }
        }, 3000);
    }
}

Address address = addressList.get(0)

You gave it junk so it is returning no results. addressList is empty. You are accessing the 0 element of something that is empty. You should have seen a message in the Android Monitor window of Android Studio that pointed you to this exact line / issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM