findFragmentById for SupportMapFragment returns null in Android Studio
Judging by the fact that you're overriding Fragment.onActivityCreated()
, I take it that your layout containing the map fragment is the layout for your Fragment
. In that case, the SupportMapFragment
is a child fragment of your hosting Fragment
. When you attempt to retrieve it, you're using the Activity
FragmentManager
. You should instead use your Fragment
's FragmentManager
:
For example, this:
SupportMapFragment m = ((SupportMapFragment) getActivity()
.getSupportFragmentManager().findFragmentById(R.id.safety_map));
becomes:
SupportMapFragment m = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.safety_map));
MapFragment return null
Update 1: getMap()
is deprecated
It is better to use getMapAsync()
method of MapFragment/SupportMapFragment
. The example how to use the method shown below (copied from their documentation).
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import android.app.Activity;
import android.os.Bundle;
public class MapPane extends Activity implements OnMapReadyCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
}
}
Quoting Google's MapFragment/SupportMapFragment
A GoogleMap can only be acquired using getMap() when the underlying
maps system is loaded and the underlying view in the fragment exists.
This class automatically initializes the maps system and the view;
however you cannot be guaranteed when it will be ready because this
depends on the availability of the Google Play services APK. If a
GoogleMap is not available, getMap() will return null.
On your code, you immediately retrieve GoogleMap
AFTER Committing MapFragment
. Wait until the MapFragment
is fully loaded on activity so you can get the GoogleMap
.
Perhaps, you can deliver the GoogleMap
from MapFragment
to Activity
using interface, like this.
public class MyMapFragment extends SupportMapFragment
{
private MapCallback callback;
public void setMapCallback(MapCallback callback)
{
this.callback = callback;
}
public static interface MapCallback
{
public void onMapReady(GoogleMap map);
}
@Override public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if(callback != null) callback.onMapReady(getMap());
}
}
public class MyActivity extends Activity implements MyMapFragment.MapCallback
{
// .........
@Override
public void onCreate(Bundle onsavedInstanceState)
{
mMapFragment = (MyMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
// We only create a fragment if it doesn't already exist.
if (mMapFragment == null) {
mMapFragment = MyMapFragment.newInstance();
mMapFragment.setMapCallback(this); // This activity will receive the Map object once the map fragment is fully loaded
// Then we add it using a FragmentTransaction.
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(MapLay.getId(), mMapFragment, MAP_FRAGMENT_TAG);
fragmentTransaction.commit();
}
else
{
mMapFragment.setMapCallback(this); // This activity will receive the Map object once the map fragment is fully loaded
}
@Override
public void onMapReady(GoogleMap map)
{
// Do what you want to map
}
}
getSupportFragmentManager().findFragmentById returns null for google maps in fragment in android?
The problem is that you're trying to use the Activity's FragmentManager, and you should be using the Fragment's child FragmentManager.
Remove the onCreate()
override in the Fragment, and add an onCreateView()
Override where you inflate the layout and call getMapAsync()
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return rootView;
}
SupportMapFragment return null on Android studio
getMap()
is not guaranteed to return a map instance. Use getMapAsync(OnMapReadyCallback)
where the callback will be invoked once the map is ready and you're guaranteed it won't be null
. This is available since Google Play Services library v6.5.
When using this approach get rid of your mapView
variable, the callback will receive a map reference anyway. Also note that SupportMapFragment
is not MapView
is not GoogleMap
(I'm referring to the misnamed variable here, be careful.).
EDIT: Suggested solution:
public class MainActivity extends ActionBarActivity {
SupportMapFragment mMapFragment;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
mMapFragment = getSupportFragmentManager().findFragmentById(R.id.map);
// etc.
}
public void doSomethingWithMap() {
mMapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
// do whatever you need with the map
}
});
}
}
The point is when you need to access the map, you ask the fragment for it, and it will be delivered to you via a callback.
SupportMapFragment.getmap() returns null
map takes some time to load, so you need to run your code in handler -->
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run() {
GoogleMap googleMap = SupportMapFragment.newInstance(new GoogleMapOptions().zOrderOnTop(true)).getMap();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.map_content, fragment);
ft.commit();
if(googleMap != null) {
googleMap.addMarker(new MarkerOptions().position(result)).setVisible(true);
// Move the camera instantly to location with a zoom of 15.
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(result, 15));
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setCompassEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
handler.removeCallbacksAndMessages(null);
}
else {
handler.postDelayed(this, 500);
}
}, 500);
findFragmentById() returns null?
Add setContentView(R.layout.pacmain_activity);
Without it you have nothing
Old question: getSupportFragmentManager returns null
AndroidXMapFragment returns null when initializing from fragment
I figured it out. Here is if anyone have troubles implementing it from Fragment.
But this is with SupportMapFragment, also works with AndroidXMapFragment
public class FragmentHome extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate (R.layout.fragment_home, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager ().findFragmentById (R.id.mapFragment);
MapFragmentView fragmentMap = new MapFragmentView ((AppCompatActivity) getActivity (), mapFragment);
return view;
}
}
In MapFragmentView constructor i have added one more parameter for SupportMapFragment
public class MapFragmentView {
private AppCompatActivity m_activity;
private SupportMapFragment mapFragment;
public MapFragmentView(AppCompatActivity activity, SupportMapFragment mapFragment) {
m_activity = activity;
this.mapFragment = mapFragment;
initialize (); // This is init map
}
}
MapFragment or MapView getMap() returns null on Lollipop
I had exactly the same problem but this is what worked for me:
Replace this...
GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
with this...
GoogleMap map = getMapFragment().getMap();
then slip this bad boy in and give it a whirl...
private MapFragment getMapFragment() {
FragmentManager fm = null;
Log.d(TAG, "sdk: " + Build.VERSION.SDK_INT);
Log.d(TAG, "release: " + Build.VERSION.RELEASE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Log.d(TAG, "using getFragmentManager");
fm = getFragmentManager();
} else {
Log.d(TAG, "using getChildFragmentManager");
fm = getChildFragmentManager();
}
return (MapFragment) fm.findFragmentById(R.id.map);
}
getSupportFragmentManager().findFragmentById(R.id.map) started returning null
I had to change
getActivity().getSupportFragmentManager()
to
getChildFragmentManager()
to get it working. No idea why it was working perfectly few days ago.
Related Topics
Getting the Battery Current Values for the Android Phone
How to Get Name of Wifi-Network Out of Android Using Android API
Launch Skype from an App Programmatically & Pass Number - Android
How to Share a Sharedpreferences File Across Two Different Android Apps
"Id Cannot Be Resolved or Is Not a Field" Error
How to Simulate Android Killing My Process
How to Provide Animation When Calling Another Activity in Android
Completely Transparent Status Bar and Navigation Bar on Lollipop
Differencebetween Background, Backgroundtint, Backgroundtintmode Attributes in Android Layout Xml
Edittext Underline Below Text Property
How to Move Bluetooth Activity into a Service
How to Send Broadcast from One App to Another App
Java.Lang.Nullpointerexception (No Error Message)
Avoid Reloading Activity with Asynctask on Orientation Change in Android
Android - Acceleration Down (Smash)
Android: How to Make Keyboard Enter Button Say "Search" and Handle Its Click