Search code examples
androidgoogle-mapsgeocodinggoogle-geocoder

Instantiating Geocoder causes NullPointerException


Instantiating the Geocoder causes my app to crash with NullPointerException.

This is my code (only single Activity):

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private final int MAX_RESULTS = 1;

    //if I comment out the following line, app will not crash
    private Geocoder geocoder = new Geocoder(getApplicationContext()); //line 27

    private GoogleMap gmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        setUpMap(map);
        gmap = map;
    }

    ...
}

I have tried new Geocoder(getBaseContext()), new Geocoder(this) and new Geocoder(MapsActivity.this) but they all crash. How to fix this?

logcat:

Caused by: java.lang.NullPointerException
            at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
            at android.location.GeocoderParams.<init>(GeocoderParams.java:50)
            at android.location.Geocoder.<init>(Geocoder.java:83)
            at android.location.Geocoder.<init>(Geocoder.java:95)
            at rubiks.cres.MapsActivity.<init>(MapsActivity.java:27)

Solution

  • Move the initialization in onCreate :

    private Geocoder geocoder;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        geocoder = new Geocoder(this);
        SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    

    getApplicationContext() is likely to return null if the Activity creation is not finished.