实例化地理编码器会导致NullPointerException

时间:2015-07-07 07:59:51

标签: android google-maps geocoding google-geocoder

实例化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)

1 个答案:

答案 0 :(得分:2)

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()创建未完成,则

null可能会返回Activity