Reputation: 1069
I am getting a java.lang.NullPointerException
on the line map.setOnMyLocationChangeListener(myLocationChangeListener);
. Strangely, this exception arises while running it some devices while in some it doesn't. How do I solve this?
public class MyMap extends ActionBarActivity implements
RoutingListener, OnMapReadyCallback,
SensorEventListener {
// private GoogleApiClient mGoogleApiClient;
protected GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();
}
mapFragment.getMapAsync(this);
map = mapFragment.getMap();
map.setOnMyLocationChangeListener(myLocationChangeListener);
}
EDIT:
@Override
public void onMapReady(GoogleMap mMap) {
map = mMap;
mUiSettings = map.getUiSettings();
mUiSettings.setZoomControlsEnabled(true);
mUiSettings.setCompassEnabled(true);
updateMyLocation();
}
Upvotes: 0
Views: 295
Reputation: 1140
By calling mapFragment.getMapAsync(this);
, I suppose you have to override this method public void onMapReady(GoogleMap googleMap)
. Set your mMap = googleMap
there and set all other listener there. Keep in mind that your Map object needs some time to be initialised, that's why they give you getMapAsync
method.
Editted:
Please remove this from your onCreated
map = mapFragment.getMap();
map.setOnMyLocationChangeListener(myLocationChangeListener);
and put them map.setOnMyLocationChangeListener(myLocationChangeListener);
inside your onMapReady()
after this line map = mMap
. Please acknowledge when your map is initialized.
Upvotes: 1
Reputation: 9700
When you work with GoogleMap
then it takes time to initialize. Sometimes it takes longer time in some devices than others.
To solve this issue, you should initialize the GoogleMap
object with some delay. You can follow the below strategy:
private Handler handler = new Handler();
private Runnable mapChecker = new Runnable() {
@Override
public void run() {
try {
if (mapFragment.getMap() != null) {
map = mapFragment.getMap();
map.setOnMyLocationChangeListener(myLocationChangeListener);
return;
}
} catch (Exception e) {
e.printStackTrace();
}
handler.postDelayed(mapChecker, 500);
}
};
Then from onCreate()
,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_map);
..........
handler.postDelayed(mapChecker, 500);
..........
}
Upvotes: 0