Skip to content Skip to sidebar Skip to footer

Geocoder Initialization Fails

I am getting a NullPointerException when trying to declare the Geocoder in my application. I have the following declaration : public class MainActivity extends Activity { private

Solution 1:

The context is only available when the activity is started so you cannot initialize the geocoder in the class body. Try to initialize it in the onCreate or onResume method instead...

publicclassMainActivityextendsActivity {
  private Geocoder mGeocoder;

  @OverrideprotectedvoidonCreate(Bundle _icicle) {
    super.onCreate(_icicle);
    mGeocoder = newGeocoder(getApplicationContext(), Locale.getDefault());
  }
}

Solution 2:

Add this permissions in to manifest

<uses-permissionandroid:name="android.permission.INTERNET" /><uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" />

and use getApplicationContext() insted of this

Solution 3:

It is recommended to use the GeoCode in Background or on separate thread as defined by Google Developers page.

newThread(newRunnable() 
                    {
                        @Overridepublicvoidrun() 
                        {
                            //Do things.Geocodergeocoder=newGeocoder(getBaseContext());


                            try {
                                // Getting a maximum of 5 Address that matches the input text
                                addresses = geocoder.getFromLocationName(addressText,5);


                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }

                    }).start();

Post a Comment for "Geocoder Initialization Fails"