findFragmentById for SupportMapFragment returns null in Android Studio
Yes. It's not work for targetSdkVersion 21, if your Map fragment is inner part of Fragment (due to some issues, that mentioned this and this).
As temporary resolving can advice such trick:
public class MyFragment extends Fragment {
private SupportMapFragment fragment;
private GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.layout_with_map, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_container, fragment).commit();
}
}
}
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));
The following code worked for me. I was using Google Map in a Fragment
:
SupportMapFragment m = ((SupportMapFragment) getChildFragmentManager() .findFragmentById(R.id.safety_map));
All the answers are correct in their respective manner. It may happen that you follow someones's java code which is working for them but not work for you because you had different implementation in your xml code than them.
So let me give you my opinion how I managed to load map in both Activity
as well as Fragment
Activity:
<fragment
android:name="com.google.android.gms.maps.MapFragment"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Java class:
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
In Fragment:
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Java class:
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);