Shahek Shahek - 4 months ago 156
Android Question

getMapAsync in Fragment

I am using Sliding Tabs with different fragments. In map fragment I cannot use Nested Fragment as XML. Below is Java code and XMLfile.
I am stuck at

getMapAsync()
method So How Can I get Map using
getMapAsync
without Any exception? I will really appreciate your cooperation.

Food Fragment Java:

public class FoodFragment extends Fragment {

private SupportMapFragment mapfragment;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.food_layout, null);

mapfragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.maps_frame);
if (mapfragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mapfragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.maps_frame,mapfragment).commit();
}
mapfragment.getMapAsync((OnMapReadyCallback) getActivity().getApplicationContext());

return view;

}
}


Food XML file,

<FrameLayout
android:layout_width="match_parent"
android:layout_height="2in"
android:id="@+id/maps_frame"
android:background="@color/colorAccent"
android:layout_alignParentBottom="true">

</FrameLayout>

Answer

Your ApplicationContext cannot be casts as OnMapReadyCallback you can create new instance of OnMapReadyCallback() as an anonymous class instead like here is what you might be searching for

  mapfragment.getMapAsync(new OnMapReadyCallback() {
        @Override public void onMapReady(GoogleMap googleMap) {
            if (googleMap != null) {
               // your additional codes goes here
               .....
            }
   }

You can refer this example as well if you need.