Search code examples
androidgoogle-maps-android-api-2google-geocoder

App Crashes when entering invalid or null location using geocoder


I have been working on google maps and want the user can access location using geocoding, although it is working but the problem arises when the user enters invalid location or null location in edit text, my app gets crashed. This is my code: (on search button click)

 public void onSearch(View view) {
        EditText addressSearch = (EditText) findViewById(R.id.edtSearchAddress);
        String location = addressSearch.getText().toString();
        List<Address> addressList = null;
        if (location != null || !location.equals("")) {
            addressSearch.setText("");
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());

            try {
                addressList=  geocoder.getFromLocationName(location, 7);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // location exists
            Address address = addressList.get(0);
            LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
            map.addMarker(new MarkerOptions().position(latLng).title("Find Pro"));
            map.animateCamera(CameraUpdateFactory.newLatLng(latLng));

        } else {
            addressSearch.setText("Location does not exist");
        }

    }

Your kind support will be appreciated.


Solution

  • According to documentation the call of geocoder.getFromLocationName can throw IllegalArgumentException or return empty list. Both cases will crash your app. My bet the list is empty.

    So guard your code:

     if (addressList.size() > 0) {
          Address address = addressList.get(0);
          LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
          map.addMarker(new MarkerOptions().position(latLng).title("Find Pro"));
          map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
     }