1

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.

Eugen Martynov
  • 19,888
  • 10
  • 61
  • 114
Pihu
  • 1,041
  • 11
  • 35

2 Answers2

0

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));
 }
Eugen Martynov
  • 19,888
  • 10
  • 61
  • 114
0

when you pass null value that time addressList return 0 value so please set IF condition before get value from addressList.

if (addressList.size() > 0) {
Address address = addressList.get(0);
}
ckpatel
  • 1,926
  • 4
  • 18
  • 34