android SupportMapFragment : java.lang.NullPointerException - android

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();
}

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.

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);
..........
}

Related

How to use getMapAsync() instead of getMap()

I am aware that in Play Services, getMap() is depreciated, and is replaced by getMapAsync().
But I am not sure how to use getMapAsync(). I found other questions similar to this -- however, in my code, I am not sure what to implement in my getMapAsync(). I think it is supposed to be a callback method, but I am not sure.
Could someone please put the correct code in, and tell me what I am doing wrong?
public class FindParty extends AppCompatActivity {
static final LatLng Durban = new LatLng(-29.858680, 31.021840);
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_party);
try{
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
final Marker marker_Durban = googleMap.addMarker(new MarkerOptions()
.position(Durban)
.snippet("Durban, KwaZulu-Natal, South Africa")
.title("Durban"));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.getTitle().equals("Durban")) {
Intent intent = new Intent(FindParty.this, Party.class);
intent.putExtra("message", "Durban");
startActivity(intent);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
your class need to implements OnMapReadyCallback
public class FindParty extends AppCompatActivity implements OnMapReadyCallback {
static final LatLng Durban = new LatLng(-29.858680, 31.021840);
private GoogleMap googleMap;
MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_party);
try {
if (googleMap == null) {
mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
final Marker marker_Durban = googleMap.addMarker(new MarkerOptions()
.position(Durban)
.snippet("Durban, KwaZulu-Natal, South Africa")
.title("Durban"));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.getTitle().equals("Durban")) {
Intent intent = new Intent(FindParty.this, Party.class);
intent.putExtra("message", "Durban");
startActivity(intent);
}
}
});
}
}
You are right, getMapAsync() is based on callback, please see belowe example and move your map options settings to callback method:
Example
getMapAsync() { it.isTrafficEnabled = false }
The better way I found to understand the use of getMapAsync was to create a new project in Android Studio and use the template of google maps activity instead of an empty activity.
Hope help others with the same difficulty.

Google maps can not resolve method getMap()

I am using google map in my project. it was working but i did something( dont know what)now getMap() gives error. i think i update something. how can i fix it?
my code is like that;
GoogleMap googleMap;
..
if (locationManagerCheck.isLocationServiceAvailable()) {
if (googleMap == null) {
try {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();//ERROR
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_SHORT)
.show();
}...
i tried make it:
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
but 'this' gives another error
can you help me?
edit:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager_check locationManagerCheck = new LocationManager_check(
this);
if (locationManagerCheck.isLocationServiceAvailable()) {
if (googleMap == null) {
try {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(final Marker marker) {....}
}
#Override
public void onMapReady(GoogleMap Map) {
googleMap=Map;
}
}
You should give a look to documentation
To add a map to an activity, add map fragment to your layout :
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.gms.maps.MapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And then use it in your activity :
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
map.setMyLocationEnabled(true);
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(final Marker marker) {....}
}
The map will be created in async way, and the onMapReady function will be called when map is ready,in this function you will be able to add markers, change position, title, zoom or whatever.
At the point you're retrieving the map it is null. You need to do it when you now the views have been initialised.
For example, in a Fragment you could do it in onViewCreated or in an Activity in onCreate after calling setContentView(R.layout.your_layout);
For example:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapView mapView = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
mapView.getMapAsync(this);
}

Got crash after adding Onmarkerclicklistener

Like title, my app crash if I add OnMarkerClickListener or OnInfoWindowClickListener. Please help me. I have updated the code
This is my code, sorry I'm newbie :|
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
btnBeHost = (Button)findViewById(R.id.btnBeHost);
requestQueue = Volley.newRequestQueue(this);
//be a host btn when clicked
...
//Welcome
...
//get coordinates of motels and show on map
//latitude request
...
//longitude request
...
RequestQueue queue = Volley.newRequestQueue(MapsActivity.this);
queue.add(latReq);
queue.add(lngReq);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this,"zzzz",Toast.LENGTH_LONG).show();
return false;
}
});
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
//set my location enabled
...
}
You are trying to call a method of mMap in your onCreate(), but mMap will be null until you assign it in onMapReady().
You will have to wait until after you assign it (perhaps later in onMap ready or in something you run subsequently) to call methods such as those which set up event listeners.

getMapAysnc(this) crashes with NullPointerException

I've been trying to setup a map using some help I got here. SO, it's very simple code but crashes. What am I doing wrong?
public class ShowDirection extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap myMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_directions);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); // causes the Exception
}
#Override
public void onMapReady(final GoogleMap map) {
this.myMap = map;
myMap.setMyLocationEnabled(true);
}
Double check if your Fragment's id is actually R.id.map because it's returning null on that line. If it is not, simply replace that with the proper id.

Instantiating Geocoder causes NullPointerException

Instantiating the Geocoder causes my app to crash with NullPointerException.
This is my code (only single Activity):
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private final int MAX_RESULTS = 1;
//if I comment out the following line, app will not crash
private Geocoder geocoder = new Geocoder(getApplicationContext()); //line 27
private GoogleMap gmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
setUpMap(map);
gmap = map;
}
...
}
I have tried new Geocoder(getBaseContext()), new Geocoder(this) and new Geocoder(MapsActivity.this) but they all crash. How to fix this?
logcat:
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
at android.location.GeocoderParams.<init>(GeocoderParams.java:50)
at android.location.Geocoder.<init>(Geocoder.java:83)
at android.location.Geocoder.<init>(Geocoder.java:95)
at rubiks.cres.MapsActivity.<init>(MapsActivity.java:27)
Move the initialization in onCreate :
private Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
geocoder = new Geocoder(this);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
getApplicationContext() is likely to return null if the Activity creation is not finished.

Categories

Resources