【发布时间】:2015-08-13 09:57:55
【问题描述】:
我正在尝试在 Fragment 中创建地图,但不断收到此错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
at com.new.newapps.activity.MapsFragment.initilizeMap(MapsFragment.java:41)
at com.new.newapps.activity.MapsFragment.onResume(MapsFragment.java:52)
我不确定如何解决这个问题。请看下面我的代码。
MapsFragment 类:
public class MapsFragment extends Fragment {
public MapsFragment(){}
GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_distance, container, false);
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map))
.getMap();
if (googleMap == null) {
Toast.makeText(getActivity(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
@Override
public void onResume() {
super.onResume();
initilizeMap();
if (googleMap != null) {
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(xx.xxxx, xx.xxxx))
.zoom(10)
.bearing(0)
.tilt(80)
.build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
}
然后在我的布局文件中:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</RelativeLayout>
这是我的 gradle 文件:
compile 'com.google.android.gms:play-services:6.5.87'
请原谅我的英语不好:-)
任何帮助将不胜感激!谢谢
【问题讨论】:
标签: android google-maps android-fragments