我正在一个片段类内的地图上工作。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