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...

public class MainActivity extends Activity {
  private Geocoder mGeocoder;

  @Override
  protected void onCreate(Bundle _icicle) {
    super.onCreate(_icicle);
    mGeocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
  }
}

Solution 2:

Add this permissions in to manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android: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.

new Thread(new Runnable() 
                    {
                        @Override
                        public void run() 
                        {
                            //Do things.
                            Geocoder geocoder = new Geocoder(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"