android


Android MapView getMap() returns null


MapView's getMap() method can return null. I know this is an intended behavior by Google.
Can someone provide a definitive description as to when and under which circumstances the getMap() method returns null?
I know that if Google Services are unavailable on the given device, getMap() will return null. This eventuality is relatively well documented. I'm more concerned with the vague other case where even when Google Services are installed on a device, getMap() can still return null.
My assumption up to this point is that there is some initialization of the underlying maps system, during which time your code might execute and get a null map.
Am I correct in my assumption?
Is there any particular place in the Activity or Fragment lifecycle where we can definitively get a non-null GoogleMap (if we assume Google Services IS installed)?
My goal in asking this question is to prevent a litany of if(mapView.getMap() != null) checks littered throughout my code. In addition, this question seems to still come up on a regular basis here on StackOverflow and I'd like to see if we can flesh out the truth behind what exactly is going on with MapView and getMap()
Scenarios handled by Google
If the google play apk is not installed you will get a null. But its somehow built in to download it from the playstore. But the playstore may not be installed so you get a null map. If the internet isn't available and the playstore is installed but google play services is not you get a null because google play services can't be installed. But coding for these senarios is done for you.
Scenarios handled by your code.
This is what you have to code for. If you deviate from the pattern outlined in the map samples you will get a null map. Every sample does it the same way. This is so if the first call in onCreate fails there is still a second chance to get the map in onResume. Your solution is to call getMap() only in one place and save the map object that is returned. Follow the basic pattern that the map samples use. In the onCreate and onResume methods you call setupmapifneeded which inturn calls setupmap when the map object is not null.
Here's the first map sample.
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gosylvester.testapp;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
/**
* This shows how to create a simple activity with a map and a marker on the map.
* <p>
* Notice how we deal with the possibility that the Google Play services APK is not
* installed/enabled/updated on a user's device.
*/
public class BasicMapActivity extends FragmentActivity {
/**
* Note that this may be null if the Google Play services APK is not available.
*/
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not have been
* completely destroyed during this process (it is likely that it would only be stopped or
* paused), {#link #onCreate(Bundle)} may not be called again so we should call this method in
* {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
Google has a more convenient way to get the map using the following method, because it might depend from a device to device to get the map ready!
Use the following method to get the map when it is ready.
myMapFragment.getMapAsync(new OnMapReadyCallback) {
#Override
public void onMapReady(GoogleMap googleMap) {
myMap = googleMap;
}
});
I have an Android Tab3 Running Android 4.2.2
All I had to do is update google maps and it did the trick.

Related Links

how to animate only one field of a recyclerView item
TextToSpeech is null in onPauseFragment
How can I style a SearchView according to its state?
Draw polygon on google map and get the selected area
Task 'connectedAndroidTest' not found in root project
UIAutomator Tests fail to start on real devices: 'java.lang.IncompatibleClassChangeError'
How to display an image in a Meteor Cordova app on Android?
Android: unable to read from sharedpreferences
android requestSingleUpdate questionable behavior
What is diff between requestIdToken and requestServerAuthCode in google singnin
Best way to save a Firebase Reference in code
Android App Shortcuts doesn't work
Android ViewPager/ListView weird display bug
Android React - Getting “Requiring unknown module react”
Android Notification.Builder vs NotificationCompat.Builder
Reusage of XML classes in Greendao

Categories

HOME
windows
beautifulsoup
xml
google-cloud-platform
facebook-oauth
twitter-bootstrap-3
gdb
cheerio
angular2-material
package
alarm
cublas
scripting
bookmarks
pearson-correlation
modal-dialog
bing-maps
spin
openstreetmap
minecraft-forge
angular-dart
google-form
gkturnbasedmatch
azure-iot-hub
job-scheduling
asp.net-mvc-viewmodel
xmonad
google-container-registry
cfml
sigma.js
bourbon
microsoft-ocr
question2answer
inno-download-plugin
string-concatenation
game-theory
maze
slidetoggle
jackson-modules
amazon-quicksight
progress-bar
genexus-sd
angular-translate
bioinformatics
anki
paragraph
laravel-eloquent
simplecv
dsx-desktop
searchkit
projects-and-solutions
gdata
metawidget
apache-stanbol
levenshtein-distance
skylink
wmp
claims
vaadin-charts
rfc3339
jide
dtsearch
podscms
remedy
video-conferencing
template-toolkit
slackware
reporting-services-2012
qtplugin
myspace
model-associations
avspeechsynthesizer
cycle2
design-principles
state-restoration
themoviedb-api
r-package
avisynth
django-urls
doctype
lasso
google-refine
mraid
java-security
gamekit
grouping-sets
dbaccess
pseudo-class
sip-server
psr-4
human-computer-interface
jqmodal
ss7
cuba
ios8-extension
oocss
apache-abdera
curb
patricia-trie
dajaxice
listitem
oracle-enterprise-linux
predicatebuilder
ilasm
event-receiver
cdonts
commerceserver2007
facebook-iframe
binomial-heap
opml
cuda.net
product-management
lemmatization
netbeans6.1

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App