实例化 Geocoder 导致 NullPointerException

Instantiating Geocoder causes NullPointerException

实例化 Geocoder 导致我的应用程序崩溃 NullPointerException

这是我的代码(只有一个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;
    }

    ...
}

我试过new Geocoder(getBaseContext())new Geocoder(this)new Geocoder(MapsActivity.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)

将初始化移动到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() 可能 return null 如果 Activity 创建未完成。