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