我有一个基于Google Maps的应用程序,并且正在使用方法getMap(),现在使用的是新模型getMapAsync,当我想清除或一般使用GoogleMap对象时遇到麻烦
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void com.google.android.gms.maps.GoogleMap.clear()'。
我正在使用片段。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_passenger_page1,
container, false);
MapFragment fm = (MapFragment) mainActivity.getFragmentManager().findFragmentById(R.id.map);
fm.getMapAsync(this);
...
}
问题在我使用时就在这里
@Override
public void onResume() {
mMap.clear();
if (listMarkers.size() > 0)
{
setMarker(listMarkers);
}
super.onResume();
}
每次打开应用程序时都会调用此函数,并说mMap为null。
请帮助我。
答案 0 :(得分:1)
请实现OnMapReadyCallback接口并覆盖
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
googleMap.clear()
if (listMarkers.size() > 0)
{
setMarker(listMarkers);
}
}
并从简历方法中删除代码
答案 1 :(得分:0)
thanks for your comments, I solved my problem by calling a clear() function in onResume, checking if the GoogleMap exists and if not creating it and passing to mMap.
@Override
public void onResume() {
clear();
if (listMarkers.size() > 0)
{
setMarker(listMarkers);
}
super.onResume();
}
The clear function looks like:
public void clear() {
GoogleMap gm = createMap();
if (gm == null) {
Log.e("clear", "The map is null"); //for testing purposes
return;
} else {
Log.e("clear", "The map already exists"); //for testing purposes
mMap = gm;
mMap.clear();
}
startLocation = null;
endLocation = null;
txtFrom.setText("");
txtTo.setText("");
}
And finally the createMap():
private GoogleMap createMap() {
if (mMap != null) {
Log.e("create", "The map already exists"); // for testing purposes
return mMap;
}
MapFragment fm = (MapFragment)
mainActivity.getFragmentManager().findFragmentById(R.id.map);
try {
fm.getMapAsync(this);
} catch (Exception ex) {
Log.e("Error", ex.getLocalizedMessage());
}
return null;
}
So in this way I always create a new GoogleMap if it doesn't exists.
If i'm doing something wrong don't hesitate to tell me :)