getSupportFragmentManager().findFragmentById return null on GoogleMap - android

I am simply trying to get my map fragment to then be able to execute getmapasync and draw markers on it. However my mapFragment value is always null. I dont understand why. I read from other answers that it might something to do with the fact that my fragment is inside a frame and therefore is some sort of child.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
startService(new Intent(MainActivity.this, TrackerService.class));
bindService(new Intent(MainActivity.this, TrackerService.class), myConnection, Context.BIND_AUTO_CREATE);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d("DEBUG", "MAP READY");
mMap = googleMap;
drawLocationMarkers();
}
And the XML:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="7dp"
android:background="#drawable/custom_card"
android:layout_weight="0.5">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/map"
class="com.google.android.gms.maps.MapFragment"/>
</FrameLayout>

You need to change your layout to use SupportMapFragment instead of MapFragment
android:name="com.google.android.gms.maps.SupportMapFragment"

Related

MapFragment is displaying but can't add markers, move camera, etc. with Google Map

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)

Google maps error inflating, Android

I get the following error when I try to leave fragment which contains map (on back button press).
ERROR: mapInflater->Binary XML file line #7: Error inflating class fragment
Bellow is onCreate() method of fragment where the map is placed. And also there is a xml code of layout.
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiRequestManager = ApiRequestManager.getInstance();
fragmentHandler = FragmentHandlerActivityMain.getInstance(getActivity());
session = new SessionManager(App.getInstance().getApplicationContext());
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(getString(R.string.maps_fragment_toolbar_name));
Handler mainHandler = new Handler();
Runnable myRunnable = new Runnable() {
#Override
public void run() {
try {
SupportMapFragment maps = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.mapView);
if (maps != null)
maps.getMapAsync(MapsFragment.this);
} catch (Exception ex) {
LogUtil.getInstance().add(LogUtil.ERROR,
TAG, "onCreateMaps", ex);
}
}
};
mainHandler.post(myRunnable);
}
Log is pointing on this layout on fragment (line 7).
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app1="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".salesman.fragments.MapsFragment">
<fragment
android:id="#+id/mapView"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"/>
</FrameLayout>
You are trying to getChildFragmentManager() instade of getSupportFragmentManager().
Need to change In Java File :
1). You need to implements OnMapReadyCallback in Your Fragment.
2). Get SupportMapFragment from View.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
3). Overrid onMapReady(GoogleMap googlMap) Method.
#Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// and move the map's camera to the same location.
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
In XML File :-
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app1="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".salesman.fragments.MapsFragment">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Please check the updated answer as per below comment:
Now try to set MapView insted of fragment because if you use fragment inside fragment it creates lot of issues.
Need to change in JAVA Code : // Initialize GoogleMap myMap; MapView mMapView;
// OnCreateView Method MapsInitializer.initialize(this.getActivity()); mMapView = (MapView) rootView.findViewById(R.id.map); mMapView.onCreate(savedInstanceState); mMapView.getMapAsync(this);
#Override public void onPause() { super.onPause(); mMapView.onPause(); }
#Override public void onPause() { super.onPause(); mMapView.onPause(); }
#Overridepublic void onResume() { super.onResume(); mMapView.onResume(); }
Need to change in XML File :
<com.google.android.gms.maps.MapView android:id="#+id/map" android:layout_width="match_parent" android:layout_height="match_parent" />

getSupportFragmentManager().findFragmentById returns null for google maps in fragment in android?

I have a problem with Google Maps, i.e. getSupportFragmentManager().findFragmentById returns always null. Do you have an idea how to solve this?
Here is the code:
fragment_map.xml:
<FrameLayout 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"
tools:context="com.myapp.something.MapFragment">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>
MapsFragment.java:
public class MapFragment extends Fragment implements OnMapReadyCallback, android.location.LocationListener
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) this.getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
...
I have Google Maps in Activity and it works with code:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
I am trying to reuse this in fragment, becouse I need maps in fragment, not in activity, but it doesn't work.
I tried:
calling this code in "onCreateView" function
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap(); is deprecated, and application crashes
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
and similar variations, but in all cases I get null for mapFragment.
Do you know how could I solve this problem?
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;
}

Why my Map fragment return null?

I have seen this and similar posts.
To me it seems that I do everything correctly.
Still,
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);`
returns NULL.
activty_map.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
<Button
android:id="#+id/startgeo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Geo"
android:background="#android:color/transparent"
android:layout_gravity="right"/>
</FrameLayout>
Code in my Activity:
setContentView(R.layout.activty_map);
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map); //RETURNS NULL !!!
map = mapFrag.getMap();
As per mentioned by some other devs, google maps take some while to load. That is why you need to call your map initialization code after some delay (lets say 500ms).
For example:
setContentView(R.layout.activty_map);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map); //should'nt be null after 500ms
map = mapFrag.getMap();
}
}, 500);
Moreover, I would suggest you to rely on onResume method for confirm completion of loading.
Rather than just posting it using some arbitrary delay you can be sure the fragment will be available in in onResumeFragments, #http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onResumeFragments()

Mapfragment findFragmentById always null

I have problems to access the fragment of the map.
getFragmentManager().findFragmentById(R.id.map)) returns always null.
I don't know why.
What's the problem?
Thank you!
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvNombreCentro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="tag_fragment_map" />
</LinearLayout>
And in the activity after the setContentView I try to access to the map, but I receive an exception
public class Mapa extends Activity {
private GoogleMap mMap;
private ActionBar ab;
private TextView tvNombreCentro;
private TextView tvTelefonoValor;
private TextView tvEMailValor;
private TextView tvWebValor;
private TextView tvDireccionValor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapa_centro);
GoogleMap mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
use this way:
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = mapFrag.getMap();
here is full code with sample:
In case your problem is not solved, try this :
As you are using SupportMapFragment, while retrieving map, use
GoogleMap mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
Also, change
public class Mapa extends Activity {
to
public class Mapa extends FragmentActivity {
I had a similar problem when trying to get MapFragment but getting null because the device didn't have Google Play Services updated.
Change in the layout
android:name = "com.google.android.gms.maps.SupportMapFragment"
by
android:name = "com.google.android.gms.maps.MapFragment".
Or, you can use getSupportFragmentManager() instead of getFragmentManager().

Categories

Resources