1
I found a code here on the site, I put in my project but it didn’t work, anyone knows how I can solve? The method below is called in onViewCreated()
Note: I am using the Map inside a Fragment, it can be this?
public class MapsFragment extends Fragment implements OnMapReadyCallback {
GoogleMap gMap;
private LatLng latLng;
private Marker marker;
private MarkerOptions markerOptions;
Onibus onibus = new Onibus();
public MapsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_maps, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
pedirPermissao();
carregarLocalizacoes();
}
public void carregarLocalizacoes() {
ArrayList<LatLng> locations = new ArrayList<LatLng>();
locations.add(new LatLng(-12.833291, -38.377971));
locations.add(new LatLng(-12.824711, -38.390898));
locations.add(new LatLng(-12.795636, -38.404648));
for (LatLng location : locations) {
if (location != null) {
markerOptions.position(location);
markerOptions.title(onibus.getRoteiro());
gMap.addMarker(markerOptions);
}
}
}
The error that appears is as follows:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.MarkerOptions com.google.android.gms.maps.model.MarkerOptions.position(com.google.android.gms.maps.model.LatLng)' on a null object reference
Welcome to Stackoverflow Elailson. Place the link to the question/answer from where you copied the code. Where you initialize the variable
markerOptions
?– Pedro Gaspar
https://stackoverflow.com/questions/30569854/adding-multiple-markers-in-google-maps-api-v2-android
– Elailson Silva
The variable is initialized just below the class creation line.
– Elailson Silva
It would be nice to put that part of the code also in the question, so because that seems to be the problem.
– Pedro Gaspar
I inserted it, but I believe that this is not the problem. The line that accuses the error is: markerOptions.position(Location);
– Elailson Silva
Yes, but there is an error on this line because you try to use the object that is stored in the variable
markerOptions
, but the variable makes no reference to any object. See Lucas' answer.– Pedro Gaspar