我正在一個片段類內的地圖上工作。NullPointer訪問地圖時出現異常
在佈局文件我已經宣佈了圖如下:
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
然後從片段onCreateView方法,我有包括以下內容:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
mapView = (MapView) v.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
map = mMap;
map.setInfoWindowAdapter(new CustomInfoWindowOrigen(LayoutInflater.from(getActivity())));
// For showing a move to my location button
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
if (location != null) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location
.getLongitude()), 14));
}
}
});
return v;
}
現在我需要添加標記或追蹤地圖上的路線,但在對地圖進行任何引用時,我會得到NullPointer異常。
喜歡這裏:
//LAS DOS DIRECCIONES
if (!direccion_origen.equals("...En espera...")){
estado_actual = "1";
if (!direccion_destino.equals("...En espera...")){
estado_actual = "3";
btnorigen.setBackgroundColor(Color.GREEN);
btndestino.setBackgroundColor(Color.GREEN);
LatLng sydney = new LatLng(-33.852, 151.211);
java.lang.NullPointerException -> map.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
我應該怎麼做才能在我的代碼添加地圖標記?
不要自己調用MapView的生命週期方法。 (或者就此而言,任何Android生命週期方法。) –
你什麼時候調用addMarker?請詳細顯示您的代碼 – redAllocator
@KevinKrumwiede,你的意思是什麼? – mvasco