我有一个ActionBar.NAVIGATION_MODE_TABS布局。第一个选项卡是在列表视图中显示结果,第二个选项卡在地图中显示。在我升级到最新版本的Google Play服务库之前,一切都很顺利。
这里用于显示地图的片段:
public class PlaceMapFragment extends Fragment {
MapView mapView;
GoogleMap map;
ResultsListener mCallback;
List<Place> places;
private HashMap<String, Place> placeMarker = new HashMap<String, Place>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
places = mCallback.getPlaces();
View rootView = inflater.inflate(R.layout.mapview, container, false);
mapView = (MapView) rootView.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
map = mapView.getMap();
setUpMap();
return rootView;
}
private void setUpMap() {
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setMyLocationEnabled(true);
/*
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
*/
// add markers
}
@Override
public void onResume() {
mapView.onResume();
super.onResume();
setUpMap();
}
@Override
public void onPause() {
mapView.onPause();
super.onPause();
}
@Override
public void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public interface ResultsListener {
public List<Place> getPlaces();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (ResultsListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement ResultsListener");
}
}
}
我收到这些错误:
04-05 03:58:22.040: E/AndroidRuntime(661): FATAL EXCEPTION: main
04-05 03:58:22.040: E/AndroidRuntime(661): java.lang.NullPointerException
04-05 03:58:22.040: E/AndroidRuntime(661): at com.tomsyweb.mapslee.fragments.PlaceMapFragment.setUpMap(PlaceMapFragment.java:54)
04-05 03:58:22.040: E/AndroidRuntime(661): at com.tomsyweb.mapslee.fragments.PlaceMapFragment.onCreateView(PlaceMapFragment.java:48)
我评论过MapsInitializer.initialize(this.getActivity());
部分,因为GooglePlayServicesNotAvailableException
会出错。
mapview.xml
<com.google.android.gms.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
我的代码取自Getting Google Map Fragment in onCreateView using ActionBar tabs
答案 0 :(得分:0)
如果设备没有安装最新版本的地图,或者可能出于其他原因,您的地图可能为空。尝试创建它甚至可能会提示用户启动其他活动来更新其设备。因此,我们建议您创建这样的initMap()
方法,并在onCreate(...)
和onResume()
中调用它:
private void initMap() {
if(map == null) {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if(map != null) {
// set up map
}
}
}