In my Android app I am showing a Google Maps map inside a class that extends Fragment.
At the moment, only the map is shown, but I am not able to obtain the map from the SupportFragmentManager.
What I have done is adapting the MapActivity that comes within Android Studio to my app.
Here is my code:
public class Tab2 extends Fragment {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private double latitud_del_hotel, longitud_del_hotel;
private String nombre_del_hotel;
private GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_2, container, false);
//setUpMapIfNeeded();
return v;
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
setUpMapIfNeeded();
}
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) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
I am getting an exception: java.lang.NullPointerException
at com.solinpromex.elpasojuarezexperience.Tab2.setUpMapIfNeeded
I have tried calling method setUpMapIfNeeded() from both methods: onCreateView and onActivityCreated. Both cases throw the exception.
If I remove setUpMapIfNeeded() then the map is shown, but I want to add map objects.
Any help is welcome..
EDIT
Complete exception log from logcat:
09-16 00:34:09.614 13999-13999/com.solinpromex.elpasojuarezexperience E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.solinpromex.elpasojuarezexperience, PID: 13999
java.lang.NullPointerException
at com.solinpromex.elpasojuarezexperience.Tab2.setUpMapIfNeeded(Tab2.java:66)
at com.solinpromex.elpasojuarezexperience.Tab2.onActivityCreated(Tab2.java:57)
at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1797)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:979)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
at android.support.v4.view.ViewPager.populate(ViewPager.java:951)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1473)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
at android.view.View.measure(View.java:16857)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1334)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1532)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1211)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6282)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
EDIT 2
Layout file tab_2
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
android:id="#+id/map"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</LinearLayout>
</RelativeLayout>
If you use the latest GooglePlayServices you can use the getMapAsync function which will automatically initializes the maps system and the view.
Also use a MapView in the layout
This is how I added the map in fragment.
public class MapFragment extends Fragment implements OnMapReadyCallback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_tab_fragment1, container, false);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
SupportMapFragment fragment = new SupportMapFragment();
transaction.add(R.id.mapView, fragment);
transaction.commit();
fragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap map) {
//map is ready
map.addMarker(...
}
}
in xml
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
To use the latest GooglePlayService put this in gradle
compile 'com.google.android.gms:play-services:8.3.0'
Follow this code.Hope this might help.Make the changes where ever necessary according to your requirement.I think you are adding this map view as a fragment in a tab view.
public class DealsCloseBy extends Fragment {
SupportMapFragment mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_deals_close_by, container, false);
mMapView = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 13.0294278;
double longitude =80.24667829999999;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps").icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_pin));
// Changing marker icon
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(13.0294278, 80.24667829999999)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
}
In xml file,in place of map fragment,use:-
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.google.android.gms.maps.SupportMapFragment"/>
Related
I'm making an application using Android Studio and even though I've got the map and it's being displayed, I can't add markers or do anything else to it using the GoogleMap object obtained from OnMapReady.
Here's the code from my Main Activity:
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener, OnMapReadyCallback {
MapFragment mapFragment;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchFragments(GlobalConsts.FRAGMENT.MAP);
}
public void switchFragments(GlobalConsts.FRAGMENT fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch (fragment) {
case MAP:
if (mapFragment == null) {
mapFragment = new MapFragment();
}
mapFragment.getMapAsync(this);
transaction.replace(R.id.fragmentContainer, mapFragment);
transaction.addToBackStack(null);
break;
}
transaction.commit();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions()
.position(sydney)
.title("Sydney")
.snippet("Population: 4,627,300")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
Here's the xml layout for my Main Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
tools:context="jarett.familymap.MainActivity">
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
My MapFragment class:
public class MapFragment extends SupportMapFragment {
public MapFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
and the xml layout for my MapFragment in fragment_map.xml:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mapFragment"
android:orientation="vertical"
android:layout_width="match_parent" android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
tools:context="jarett.familymap.MapFragment">
</fragment>
Like I said, everything seems to be working fine as far as displaying the map fragment but for the life of me I can't figure out why the code for zooming and adding markers isn't doing anything. I appreciate the help.
I can't figure out why the code for zooming and adding markers isn't doing anything
Well, you have two maps. Your MapFragment extends SupportMapFragment, so that will give you one map. Then, your MapFragment inflates a layout that, in turn, creates a SupportMapFragment. This gives you two maps.
Either:
Delete MapFragment entirely, along with its associated layout file, and just have your activity create a SupportMapFragment, or
Delete your onCreateView() method from MapFragment, and move your map-management code into MapFragment, triggered by a getMapAsync() call in onViewCreated() (as I worry that you are calling it too soon in your existing code)
In my project im trying to implementthis solution for managing a map in a dynamic added fragment.
public class MapFragment extends Fragment {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v =inflater.inflate(R.layout.fragment_map, container, false);
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_arrow)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(KIEL, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
return v;
}
}
My view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/ColorBackground"
tools:context="com.example.sven.questy.GameFragments.MapFragment">
<fragment
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
WHen i run the app i get a nullpointer exception on:
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
The id of the map = map ( android:id="#+id/map").
Why the nullpointer?
Since you are using nested fragments, you should use getChildFragmentManager()
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
And I recommend you to use getMapAsync method, because getMap is deprecated
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
setupMap(googleMap);
}
});
You need to use findViewById on the view you get, not using the fragment manager. The map is attached to the view
View v =inflater.inflate(R.layout.fragment_map, container, false);
map = v.findViewById(R.id.map))
.getMap();
i am working with swipeable tabs and want to display a mapsfragment inside the second tab, but everytime i try to get access to the map, there appears a nullpointerexception. Following the code of my Fragment/Tab.
public class tab2_advanced extends Fragment implements OnMapReadyCallback{
private GoogleMap gmap;
private static View view;
MapView ourMap;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab2_erweitertezusage, container, false);
Log.i("TAB2", "Start.");
//without the following lines regarding null or not null, the fragment loads the map, but i want to set markers and select a position on the map.
if (gmap==null) {
Log.i("Tab2", "Map null");
gmap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
gmap.setMyLocationEnabled(true);
}
if (gmap != null) {
Log.i("Tab2", "Map not null");
gmap.setMyLocationEnabled(true);
}
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
Log.i("Aufruf onMapReady", "Darstellung"+gmap);
//Später Übergabe der Pos aus DB
LatLng sidney= new LatLng(49.7685, 9.9382);
gmap.setMyLocationEnabled(true);
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(wuerzburg, 13));
gmap.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(wuerzburg));
}
My XML-File for this is the following:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="50dp">
<LinearLayout
android:orientation="vertical"
android:id="#+id/layoutMap"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="200dp"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Without the described part in comments in the code of the fragment, the map loads the content. There are still some parts missing in the case, if the map is not null, but i tried it and it lands everytime in null with a following NullpointerException.
Hoping for hints :)
Greetings
Okay, i solved the issue by:
if (gmap==null) {
Log.i("Tab2", "Map null");
gmap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
gmap.setMyLocationEnabled(true);
}
if (gmap != null) {
Log.i("Tab2", "Map not null");
gmap.setMyLocationEnabled(true);
gmap.getUiSettings().setZoomControlsEnabled(true);
actLocation.getLocation(getActivity(), locationResult);
LatLng actPos = new LatLng(organizerGPS.latitude, organizerGPS.longitude);
Log.i("tab2", "actPos: " + actPos);
gmap.setMyLocationEnabled(true);
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(actPos, 13));
...
The hint with the getChildFragmentManager was good, but the reason for the NullpointerException was, that the view was null and that results to the error. Now the initialisation of the map is right behind setting the view and in addition i added a test.
I have implemented a google map in my android project in a fragment. When I load the fragment the first time it calls an async tasks and loads the markers and displays correctley.
But if I move to another fragment and then come back to the map it crashes once it tries to load again.
My error is:
android.view.InflateException: Binary XML file line #4: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
at android.view.LayoutInflater.inflate(LayoutInflater.java)
at android.view.LayoutInflater.inflate(LayoutInflater.java)
at com.beerportfolio.beerportfoliopro.BreweryMap.onCreateView(BreweryMap.java:28)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #4: Duplicate id 0x7f09003f, tag null, or parent id 0x0 with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:296)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java)
at android.view.LayoutInflater.inflate(LayoutInflater.java)
at android.view.LayoutInflater.inflate(LayoutInflater.java)
at com.beerportfolio.beerportfoliopro.BreweryMap.onCreateView(BreweryMap.java:28)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(NativeStart.java)
In the error it says something about a duplicate so I assumed it was having trouble re-loading the map markers, so I tried to place a clear markers at the start but that doesn't fix it.
My code for my map is:
public class BreweryMap extends Fragment {
public BreweryMap(){}
String beerId = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_brewmap, container, false);
setHasOptionsMenu(true);
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
GoogleMap mMap;
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.clear();
//add url
String url = "myURL";
//call async to get breweries to add to
new GetVisitedBreweries(getActivity(), mMap).execute(url);
return rootView;
}
The async tasks gets JSON parses the information and loads the map markers onto the map.
From this link..Check it..
you declare the fragment programatically, not in XML. This probably means nesting layouts.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Lots of fancy layout -->
<RelativeLayout
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</RelativeLayout>
</RelativeLayout>
Then you need to create your fragment programatically, but it needs to be done carefully with consideration for the Fragments lifecycle (http://developer.android.com/reference/android/app/Fragment.html#getChildFragmentManager()). To ensure everything is created at the right time, your code should look like this.
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);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, fragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
if (map == null) {
map = fragment.getMap();
map.addMarker(new MarkerOptions().position(new LatLng(0, 0)));
}
}
}
I recently ran into a nearly identical problem and the code below was my solution. You should be able to just rename things and add in your extra code to do what you want to do.
public class TrackerFragment extends Fragment {
private SupportMapFragment mMap;
private GoogleMap googleMap;
//private boolean chronoRunning = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag3_action, container, false);
activityBody();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
mMap = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (mMap == null) {
mMap = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, mMap).commit();
}
}
#Override
public void onResume() {
super.onResume();
if (googleMap == null) {
googleMap = mMap.getMap();
googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)));
}
}
I am too late, but this worked after lot of search
Do It Programmatically, use normal FrameLayout in xml.
SupportMapFragment mapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.map, mapFragment);
fragmentTransaction.commit();
mapFragment.getMapAsync(this);
I have the following code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup view = (ViewGroup) inflater.inflate(R.layout.fragment_left, null);
// test
SupportMapFragment fragment = new SupportMapFragment();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.map, fragment).commit();
GoogleMap googleMap = fragment.getMap();
if(getCameraPosition() == null) { // first time in app
setCameraPosition(new CameraPosition(getYourLatLng(), 12, 0 ,0));
}
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(getCameraPosition()));
googleMap.addMarker(new MarkerOptions()
.title("Your Position")
.snippet("This is where your smartphone is located.")
.position(getYourLatLng()));
return view;
}
This is what I'm trying to replace in the xml file:
<FrameLayout
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Whats up with this? Anyway to update the id?
NEW Stack Trace:
10-29 22:37:52.277: E/AndroidRuntime(16273): FATAL EXCEPTION: main
10-29 22:37:52.277: E/AndroidRuntime(16273): java.lang.NullPointerException: CameraUpdateFactory is not initialized
10-29 22:37:52.277: E/AndroidRuntime(16273): at com.google.android.gms.internal.s.b(Unknown Source)
10-29 22:37:52.277: E/AndroidRuntime(16273): at com.google.android.gms.maps.CameraUpdateFactory.aX(Unknown Source)
You need to set a MapReadyCallback.
https://developers.google.com/android/reference/com/google/android/gms/maps/MapFragment
When the map is ready, you can move the Camera. (There is a function providing a GoogleMap that allow you to move camera.)
https://developers.google.com/android/reference/com/google/android/gms/maps/OnMapReadyCallback.html