Mandeep Chaudhary
Mandeep Chaudhary

Reputation: 55

Geocoder getfromlocationName crashes app

I am trying to create a simple function in which one can find information from postcode. In the codes provided below if i enter a valid postcode it works fully. But problem starts when i enter a wrong postcode. I tried using statements try catch but instead of showing error the complete app crashes. I would also like to know how to restrict search only in UK. Is there any better option in finding addresses via postcode instead of using getfromlocationName function.

public void finder(String query){
      Geocoder geocoder;
      List<Address> addresses = new ArrayList<Address>();
      geocoder = new Geocoder(this, Locale.getDefault());

      try {
          //addresses = geocoder.getFromLocation(51.283973, 1.064928, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
          addresses = geocoder.getFromLocationName(query,1);
      } catch (Exception e) {

          Toast.makeText(MainActivity.this, "Fail " + e.getMessage(), Toast.LENGTH_SHORT).show();
      }

      String street = addresses.get(0).getThoroughfare();
      Log.i("I0",street);


      String city = addresses.get(0).getLocality();
      Log.i("I1",city);

      String county = addresses.get(0).getSubAdminArea();
      Log.i("I2",county);

      String country = addresses.get(0).getCountryName();
      Log.i("I3",country);
      String postalCode = addresses.get(0).getPostalCode();
      Log.i("I4",postalCode);

      display.setText(street + "\n" + city + "\n" + country + "\n" + postalCode  ); }

error is

07-13 21:15:26.717 10744-10744/com.example.mandeep.testing I/i1: ct3456
07-13 21:15:26.856 10744-10744/com.example.mandeep.testing D/AndroidRuntime: Shutting down VM
07-13 21:15:26.857 10744-10744/com.example.mandeep.testing E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.mandeep.testing, PID: 10744
                                                                             java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                                                                                 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                                                 at java.util.ArrayList.get(ArrayList.java:308)
                                                                                 at com.example.mandeep.testing.MainActivity.finder(MainActivity.java:85)
                                                                                 at com.example.mandeep.testing.MainActivity$1.onQueryTextSubmit(MainActivity.java:47)
                                                                                 at android.widget.SearchView.onSubmitQuery(SearchView.java:1197)
                                                                                 at android.widget.SearchView.access$900(SearchView.java:92)
                                                                                 at android.widget.SearchView$8.onEditorAction(SearchView.java:1175)
                                                                                 at android.widget.TextView.onEditorAction(TextView.java:4473)
                                                                                 at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:139)
                                                                                 at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:304)
                                                                                 at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                 at android.os.Looper.loop(Looper.java:135)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5219)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
07-13 21:15:26.878 10744-10744/? I/Process: Sending signal. PID: 10744 SIG: 9

I tried

if(addresses != null && addresses.size() > 0) {

          String street = addresses.get(0).getThoroughfare();
          Log.i("I0", street);


          String city = addresses.get(0).getLocality();
          Log.i("I1", city);

          String county = addresses.get(0).getSubAdminArea();
          Log.i("I2", county);

          String country = addresses.get(0).getCountryName();
          Log.i("I3", country);
          String postalCode = addresses.get(0).getPostalCode();
          Log.i("I4", postalCode);

          display.setText(street + "\n" + city + "\n" + country + "\n" + postalCode);
      }
      else{
          Toast.makeText(MainActivity.this, "No Results Found", Toast.LENGTH_SHORT).show();
      }

still the same problem.

I have edited the code now

public void finder(String query){
      Geocoder geocoder;
      List<Address> addresses = new ArrayList<Address>();
      geocoder = new Geocoder(this, Locale.getDefault());

      try {
          //addresses = geocoder.getFromLocation(51.283973, 1.064928, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
          addresses = geocoder.getFromLocationName(query,1);
      } catch (Exception e) {

          Toast.makeText(MainActivity.this, "Fail " + e.getMessage(), Toast.LENGTH_SHORT).show();
      }

      Log.i("yes",addresses.size() + "");

      if(addresses != null && addresses.size() > 0) {
          Log.i("yes","checked");

          String street = addresses.get(0).getThoroughfare();
          Log.i("I0", street);


          String city = addresses.get(0).getLocality();
          Log.i("I1", city);

          String county = addresses.get(0).getSubAdminArea();
          Log.i("I2", county);

          String country = addresses.get(0).getCountryName();
          Log.i("I3", country);
          String postalCode = addresses.get(0).getPostalCode();
          Log.i("I4", postalCode);

          display.setText(street + "\n" + city + "\n" + country + "\n" + postalCode);
      }
      else{
          Toast.makeText(MainActivity.this, "No Results Found", Toast.LENGTH_SHORT).show();
      }


  }

and now the error is

07-13 22:21:02.782 32088-32088/com.example.mandeep.testing I/i1: ct28dx
07-13 22:21:02.942 32088-32088/com.example.mandeep.testing I/yes: 1
07-13 22:21:02.942 32088-32088/com.example.mandeep.testing I/yes: checked
07-13 22:21:02.942 32088-32088/com.example.mandeep.testing D/AndroidRuntime: Shutting down VM
07-13 22:21:02.944 32088-32088/com.example.mandeep.testing E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.mandeep.testing, PID: 32088
                                                                             java.lang.NullPointerException: println needs a message
                                                                                 at android.util.Log.println_native(Native Method)
                                                                                 at android.util.Log.i(Log.java:160)
                                                                                 at com.example.mandeep.testing.MainActivity.finder(MainActivity.java:93)
                                                                                 at com.example.mandeep.testing.MainActivity$1.onQueryTextSubmit(MainActivity.java:52)
                                                                                 at android.widget.SearchView.onSubmitQuery(SearchView.java:1197)
                                                                                 at android.widget.SearchView.access$900(SearchView.java:92)
                                                                                 at android.widget.SearchView$8.onEditorAction(SearchView.java:1175)
                                                                                 at android.widget.TextView.onEditorAction(TextView.java:4473)
                                                                                 at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:139)
                                                                                 at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:304)
                                                                                 at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                 at android.os.Looper.loop(Looper.java:135)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5219)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
07-13 22:21:02.973 32088-32088/com.example.mandeep.testing I/Process: Sending signal. PID: 32088 SIG: 9

Upvotes: 0

Views: 1379

Answers (4)

moonkin
moonkin

Reputation: 493

I had the same problem, then I declared a variable with default value at the beginning, so if there's an answer to the request you overwrite the variable if not the default value will be returned. In that case you can simply write "Something doesn't work correctly, please try again" or something like that.

   fun getCountryCodeFromName(locationName: String = "California"): String {
    var postalCode:String = "00000"
    try {
        if (find(locationName).size !=0)
           countryCode = cityNameReq(locationName)[0].postalCode

    } catch (e: Exception) {
        resultMessage = Resources.getSystem().getString(R.string.catch_me)
        Log.e(TAG, resultMessage, e)
    }

    return postalCode
}

Basically

                         `var postalCode:String = "00000"` 

will be returned if the program doesn't go to the try block and catches an exception.

and if the request is successful the postalCode gets the new value assigned to it as you see in this line:

      countryCode = cityNameReq(locationName)[0].postalCode

PS: It's late for the questioner, I know, but I send my answer for those who still might have this problem and are looking for an answer:

Upvotes: -1

AndrewR
AndrewR

Reputation: 10889

As already mentioned, don't assume Geocoder.getFromLocationName() always returns results. It can return an empty array.

Also:

  • Address.getLocality(), Address.getAdminArea() etc. can return null. You have to check for this.
  • Don't assume the number of lines in Address.getAddressLine(int). Check how many lines are actually returned with Address.getMaxAddressLineIndex().

Upvotes: 0

levi_kotlinman
levi_kotlinman

Reputation: 11

This line geocoder.getFromLocationName(query,1); returned an empty List. It could be because no matches were found or there is no backend service available (according to https://developer.android.com/reference/android/location/Geocoder.html). You should check if addresses != null && addresses.size() > 0 is true before performing operations with your list.

Upvotes: 0

Harish Kamboj
Harish Kamboj

Reputation: 907

You should check your array's size first

if(addresses.size() > 0){
    String street = addresses.get(0).getThoroughfare();
          Log.i("I0",street);


          String city = addresses.get(0).getLocality();
          Log.i("I1",city);

          String county = addresses.get(0).getSubAdminArea();
          Log.i("I2",county);

          String country = addresses.get(0).getCountryName();
          Log.i("I3",country);
          String postalCode = addresses.get(0).getPostalCode();
          Log.i("I4",postalCode);

          display.setText(street + "\n" + city + "\n" + country + "\n" + postalCode  ); 
}

you are tring to get data from index 0 but your list is empty.

Upvotes: 2

Related Questions