I am using actionbarsherlock to implement a set of tabs. One of the tabs is a fragment containing a MapView. My onCreateView is as follows:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.mapview, container, false);
mMapView = (MapView) view.findViewById(R.id.mapv);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try
{
MapsInitializer.initialize(getActivity());
}
catch (GooglePlayServicesNotAvailableException e)
{
e.printStackTrace();
}
googleMap = mMapView.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PARIS, 10));
googleMap.addMarker(new MarkerOptions().position(PARIS).title("Paris").snippet("Great city"));
return view;
}
As you can see, the map is originally displayed zoomed in on Paris, which has a Marker on it. Everything is working fine so far. I see the map and can manually drag and zoom the map. If I then press the button on the side of my phone to cause it to pause, then unlock the phone to resume, I can still drag and zoom. BUT if I switch to another tab, then come back to the map tab, I see the map as I left it, but it no longer responds to drag/zoom. It appears frozen. But no errors are being displayed in my log and I can still flip between tabs.
Without any log errors, I don't know how to track down the problem.
EDIT: I'm using Maps v2
EDIT: I've just found a similar sounding situation here. It may well be the answer, but I don't know quite where to place the code from the suggested solution.
EDIT: Just in case the critical code was not in my snippet, here's the whole thing...
package com.mycompany.myapp;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.view.View;
public class TestMapFragment extends Fragment implements TabListener
{
private Fragment mFragment;
private MapView mMapView;
private GoogleMap googleMap;
private static final LatLng PARIS = new LatLng(48.874,2.347);
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.mapview, container, false);
mMapView = (MapView) view.findViewById(R.id.mapv);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try
{
MapsInitializer.initialize(getActivity());
}
catch (GooglePlayServicesNotAvailableException e)
{
e.printStackTrace();
}
googleMap = mMapView.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PARIS, 10));
googleMap.addMarker(new MarkerOptions().position(PARIS).title("Paris").snippet("Great city"));
return view;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
mFragment = new TestMapFragment();
ft.add(android.R.id.content, mFragment);
ft.attach(mFragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
/*
* Using a mapview in a fragment requires you to 'route'
* the lifecycle events of the fragment to the mapview
*/
#Override
public void onResume()
{
super.onResume();
if (mMapView != null)
{
mMapView.onResume();
}
}
#Override
public void onPause()
{
super.onPause();
if (mMapView != null)
{
mMapView.onPause();
}
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mMapView != null)
{
mMapView.onDestroy();
}
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mMapView != null)
{
mMapView.onSaveInstanceState(outState);
}
}
#Override
public void onLowMemory()
{
super.onLowMemory();
if (mMapView != null)
{
mMapView.onLowMemory();
}
}
}
This added line container.removeAllViewsInLayout() seems to have done the trick.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
container.removeAllViewsInLayout();
View view = inflater.inflate(R.layout.mapview, container, false);
i also had the same problem
i have done something like this
Fragment activity which will hold the fragments
Map_main_screen.java
public class Map_main_screen extends FragmentActivity {
private static final String[] CONTENT = new String[] { "TAB one",
"Second tab GOOGLE MAP", };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.map_new);
FragmentPagerAdapter adapter = new GoogleMusicAdapter(
getSupportFragmentManager());
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
==========================new_class_GoogleMusicAdapter============================
class GoogleMusicAdapter extends FragmentPagerAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return Map_google_TestFragment.newInstance(CONTENT[position
% CONTENT.length]);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {
return CONTENT.length;
}
}
// =================adapter ends here===============================
}
Map_google_TestFragment.java
public final class Map_google_TestFragment extends Fragment {
private static final String KEY_CONTENT = "TestFragment:Content";
Typeface tf;
public static Map_google_TestFragment newInstance(String content) {
Map_google_TestFragment fragment = new Map_google_TestFragment();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1; i++) {
builder.append(content).append(" ");
}
builder.deleteCharAt(builder.length() - 1);
fragment.mContent = builder.toString();
return fragment;
}
private String mContent = "???";
private int[] mICONS = { 1 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null)
&& savedInstanceState.containsKey(KEY_CONTENT)) {
mContent = savedInstanceState.getString(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View v;
if (mContent.toString().equals("TAB one")) {
v = vi.inflate(R.layout.YOUR_SECOND_LAYOUT, null);
//***************************************
// function related to your first fragment
//***************************************
} else {
//***************************************
// inflate your Google map layout here
// function related to your Second fragment
//***************************************
View view = inflater.inflate(R.layout.mapview, container, false); //INFLATE GOOGLE MAP LAYOUT
mMapView = (MapView) view.findViewById(R.id.mapv);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try
{
MapsInitializer.initialize(getActivity());
}
catch (GooglePlayServicesNotAvailableException e)
{
e.printStackTrace();
}
googleMap = mMapView.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PARIS, 10));
googleMap.addMarker(new MarkerOptions().position(PARIS).title("Paris").snippet("Great city"));
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_CONTENT, mContent);
}
}
Have you tried using mMapView.displayZoomControls(true) right after mMapView = (MapView) view.findViewById(R.id.mapv)?
Related
We're trying to track down a memory leak happening on the GoogleMap in our Android app, which ends in an OOM after about 40-50 device rotations. The map gets set around 3500 markers.
The App has a minSDK of 9 and therefore using the SupportMapFragment from the V4 Support Library.
We've tried multiple things including:
Caching the LatLng's
Caching CameraUpdates
Removing markers from map
Removing listeners from map
Removing all listeners, markers etc so that we just have a plain map
Updating Google Play Services library
Updating Support library
Analyzing the memory dump in MAT shows that we accumulate lots of instances of
com.google.android.gms.location.internal.LocationClientHelper$ListenerTransport
which we have no clue where they are coming from.
Anyone has an idea on what could be the cause of this memory leak?
The following code has already all markes and listeners removed and still leaks. First the base class:
public abstract class BaseMapFragment extends Fragment {
public static final int MENU_ITEM_ID_SEARCH= 102;
public static final int MENU_ITEM_ID_SHOW_LIST= 100;
public static final int ZOOM_LEVEL_DEFAULT= 14;
private static final String SAVED_INSTANCE_LATITUDE= "savedLatitude";
private static final String SAVED_INSTANCE_LONGITUDE= "savedLongitutde";
private static final String SAVED_INSTANCE_ZOOM= "savedZoom";
protected static final String CLASSTAG= BaseMapFragment.class.getSimpleName();
private GoogleMap mMap;
private CameraUpdate mResumeCameraUpdate= null;
private double mSavedLatitude;
private double mSavedLongitude;
private float mSavedZoom;
private static View mView;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mMap != null) {
outState.putDouble(SAVED_INSTANCE_LATITUDE, mMap.getCameraPosition().target.latitude);
outState.putDouble(SAVED_INSTANCE_LONGITUDE, mMap.getCameraPosition().target.longitude);
outState.putFloat(SAVED_INSTANCE_ZOOM, mMap.getCameraPosition().zoom);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (savedInstanceState != null) {
mSavedLatitude= savedInstanceState.getDouble(SAVED_INSTANCE_LATITUDE, Constants.EXTRA_VALUE_NONE);
mSavedLongitude= savedInstanceState.getDouble(SAVED_INSTANCE_LONGITUDE, Constants.EXTRA_VALUE_NONE);
mSavedZoom= savedInstanceState.getFloat(SAVED_INSTANCE_ZOOM, Constants.EXTRA_VALUE_NONE);
}
if (mView != null) {
ViewGroup parent= (ViewGroup) mView.getParent();
if (parent != null)
parent.removeView(mView);
}
try {
mView= inflater.inflate(R.layout.map_layout, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
return mView;
}
protected GoogleMap initializeMap() {
if (mMap != null) {
if (mSavedLatitude != Constants.EXTRA_VALUE_NONE && mSavedLatitude != 0.0) {
mResumeCameraUpdate= Context.getCamUpdate(mSavedZoom, mSavedLatitude, mSavedLongitude);
} else {
mResumeCameraUpdate= Context.getCamUpdate(mMap.getCameraPosition().zoom, mMap.getCameraPosition().target.latitude, mMap.getCameraPosition().target.longitude);
}
}
SupportMapFragment mapFragment= (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
if (mapFragment == null) {
mapFragment= (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment == null) {
MapsInitializer.initialize(getActivity());
mapFragment= SupportMapFragment.newInstance();
mMap= mapFragment.getMap();
} else {
mMap= mapFragment.getMap();
}
} else {
mMap= mapFragment.getMap();
}
// check if map is created successfully or not
if (mMap == null) {
Toast.makeText(getActivity().getApplicationContext(), R.string.map_create_unable, Toast.LENGTH_SHORT).show();
} else {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (mMap.getMyLocation() != null) {
CameraUpdate newLatLngZoom= Context.getCamUpdate(ZOOM_LEVEL_DEFAULT, mMap.getMyLocation());
mMap.animateCamera(newLatLngZoom);
} else {
Toast.makeText(getActivity().getApplicationContext(), R.string.map_location_services_disabled, Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
return mMap;
}
}
Subclass
public class MySupportMapFragment extends BaseMapFragment {
private LinearLayout mStaoButtonsLayout;
private ToggleButton mStaoButton;
private ToggleButton mGasStaoButton;
private Boolean mInitialLocationChange;
private CameraUpdate mResumeCameraUpdate;
private GoogleMap mMap;
private double mBundleLatitude;
private double mBundleLongitude;
#Override
public void addRequiredModelClasses(LinkedHashSet<Class<? extends ComergeModel<?>>> set) {
set.add(AboModel.class);
set.add(StationModel.class);
super.addRequiredModelClasses(set);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putDouble(BUNDLE_EXTRA_CENTER_LATITUDE, mBundleLatitude);
outState.putDouble(BUNDLE_EXTRA_CENTER_LONGITUDE, mBundleLongitude);
}
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(showSearchButton());
final StationModel stationModel= getContext().getModel(StationModel.class);
mStaoButtonsLayout= (LinearLayout) getActivity().findViewById(R.id.mapStaoButtons);
mStaoButtonsLayout.setVisibility(View.VISIBLE);
mStaoButton= (ToggleButton) mStaoButtonsLayout.findViewById(R.id.staoButton);
mStaoButton.setChecked(stationModel.isStationButtonChecked());
mGasStaoButton= (ToggleButton) mStaoButtonsLayout.findViewById(R.id.gasStaoButton);
mGasStaoButton.setChecked(stationModel.isGasStationButtonChecked());
mMap= initializeMap();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
addSearchButton(menu);
}
}
I had a similar problem before. I added following code to solve my problem:
#Override
public void onDestroy() {
if (mMap != null) {
mMap.setMyLocationEnabled(false);
}
}
It seems that LocationClientHelper$ListenerTransport is related to setMyLocationEnabled(). I had to unregister some callbacks to prevent memory leak.
i try to create a map in a fragment in a swipe view, but with this code i have a error in logcat, this is the code:
public class Mapa extends Fragment {
private static final double MARKER_LATITUDE = 42.027325;
private static final double MARKER_LONGITUDE = -8.640842;
GoogleMap map;
private FragmentActivity myContext;
public Mapa() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Mapa newInstance() {
Mapa fragment = new Mapa();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.mapa, container, false);
final LatLng position = new LatLng(MARKER_LATITUDE, MARKER_LONGITUDE);
// camera position
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener()
{
#Override
public void onCameraChange(CameraPosition arg0)
{
CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(position, 17);
map.animateCamera(cu);
map.setOnCameraChangeListener(null);
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
return android;
}
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = getFragmentManager().findFragmentById(R.id.mapFragment);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
}
and this is the logcat error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setOnCameraChangeListener(com.google.android.gms.maps.GoogleMap$OnCameraChangeListener)' on a null object reference
at greetrack.estg.ipvc.greentrack.Mapa.onCreateView(Mapa.java:49)
its my first application using maps, maybe somethings is wrong
You havent setup map, its null. So the null reference.
Map = ((MapFragment) getFragmentManager().findFragmentById(
R.id.mapView)).getMap();
is one way, or potentially following googles recommendation. Here is a maps fragment xml.
The xml file i put in isn't showing https://developers.google.com/maps/documentation/android/start#get_an_android_certificate_and_the_google_maps_api_key here is the linkk to it.
Add the following code in MainActivity.java.
package com.example.mapdemo;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I have a MainActivity which has an ActionBar with two tab, the first tab is to show the sensor data value and the second tab I want to show the Map.
But I have a problem to implement the map in the fragment on the second tab
The MainActivity is shown as below:
public class MainActivity extends Activity
{
private static final String DATA_FRAGMENT_BAR = "Data";
private static final String MAP_FRAGMENT_BAR = "Map";
private DataCollection mDataCollection;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Config.mContext = this;
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME| ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab dataTab = actionBar.newTab().setText(DATA_FRAGMENT_BAR);
ActionBar.Tab mapTab = actionBar.newTab().setText(MAP_FRAGMENT_BAR);
Fragment dataFragment = new FragmentData();
Fragment mapFragment = new FragmentMap();
dataTab.setTabListener(new MyTabsListener(dataFragment));
mapTab.setTabListener(new MyTabsListener(mapFragment));
actionBar.addTab(dataTab);
actionBar.addTab(mapTab);
mDataCollection = DataCollection.getInstance();
}
....
}
The TabsListener is shown as below
public class MyTabsListener implements ActionBar.TabListener
{
private Fragment fragment;
public MyTabsListener(Fragment fragment)
{
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.remove(fragment);
}
}
The the map fragment class is shown as below:
public class FragmentMap extends Fragment
{
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_map, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
//map.getUiSettings().setMyLocationButtonEnabled(false);
//map.setMyLocationEnabled(true);
map.addMarker(new MarkerOptions().position(new LatLng(50.167003,19.383262)));
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try
{
MapsInitializer.initialize(this.getActivity());
}
catch (GooglePlayServicesNotAvailableException e)
{
e.printStackTrace();
}
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume()
{
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy()
{
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory()
{
super.onLowMemory();
mapView.onLowMemory();
}
}
I set a break point in the FragmentMap class at the line "mapView.onCreate(savedInstanceState);" the savedInstanceState is null and the program will crash after line.
Can someone help. Thanks in advance.
Google released the Map API Version 2. This gives you a MapFragment and a SupportMapFragment. This allows you to add a Map without extending MapActivity.
Google Maps v2 In fragment cashes when clicked twice
It is not really clear in the documentation, but the MapView.onCreate() method should be called in the Fragment.onActivityCreated(), not in Fragment.onCreate()
Also, MapView.getMap() can return null, don't forget to check with that.
And you should call super.onResume() before mapView.onResume()
I have a very simple SupportMapFragment to display a small Google map which I use in this view
The idea is that the user can click it to view a full screen map.
How can I get rid of the +/- button from the map?
If it's not possible, is there an alternative method to get a map?
Here is my MapFragment code:
public class CustomMapFragment extends SupportMapFragment {
private static LatLng mPosFija;
public CustomMapFragment() {
super();
}
public static CustomMapFragment newInstance(LatLng position) {
CustomMapFragment fragment = new CustomMapFragment();
mPosFija = position;
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getMap() != null) {
initMap();
Log.d(getClass().getSimpleName(), "Map ready for use!");
}
}
#Override
public void onResume() {
super.onResume();
initMap();
}
private void initMap() {
Log.v("CustomMapFragment", "initMap");
if (getMap() != null) {
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(true);
settings.setMyLocationButtonEnabled(false);
getMap().clear();
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(mPosFija, 5));
getMap().addMarker(new MarkerOptions().position(mPosFija).draggable(false));
}
}
}
This is the code for my DialogFragment that adds the mapFragment to the view:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) == ConnectionResult.SERVICE_INVALID
|| GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) == ConnectionResult.SERVICE_MISSING) {
Log.e("HERE", "Google play not active");
TextViewFragment tvf = new TextViewFragment();
getChildFragmentManager().beginTransaction().replace(R.id.mapview, tvf).commit();
} else {
CustomMapFragment mMapFragment = CustomMapFragment.newInstance(new LatLng(offer.latitude, offer.longitude));
getChildFragmentManager().beginTransaction().replace(R.id.mapview, mMapFragment).commit();
}
}
Ok, so this was staring me in the face and was as simple as
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(false);
settings.setMyLocationButtonEnabled(false);
settings.setZoomControlsEnabled(false);
I have a question and a problem. First of all I don't know is this possible:
I have a fragment activity with tabs. On one tab (which is a fragment) I have a map with a hidden list of items. Map is putted in a frame of that fragment. The list is downloaded and on a button press is visible again. On a map I have markers that represents that items.
My problem is this: I always get map to be null when a use getMap() from a fragment that I put in a frame.
Is this possible? And if not what do you recommend? Thanks in advance.
EDITED
public class MapExplore extends Fragment{
private FrameLayout frame;
private ListView list;
private String api_key;
private GoogleMap map;
private MapExploreAdapter adapter;
private SupportMapFragment map_fragment;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
api_key = Configuration.get_prefereence_string(getActivity(), "user_activation_key", null);
adapter = new MapExploreAdapter();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_explore, null);
frame = (FrameLayout) view.findViewById(R.id.frameMap);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setUpMapFragment();
}
private void setUpMapFragment(){
if(map_fragment == null){
map_fragment = SupportMapFragment.newInstance();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.add(frame.getId(), map_fragment, Utils.MAP_FRAGMENT_TAG);
ft.commit();
}
}
private void setUpMap(){
Log.i("SET UP MAP", "Started");
if(map == null){
map = ((SupportMapFragment) map_fragment).getMap();
}
if(map != null){
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Utils.SF_LAT, Utils.SF_LON), 13));
}
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
setUpMap();
}
I edited my question with some code...
If you could post some of you code it would be easier to diagnose your problem:
meantime try creating your SupportMap fragment dynamically as follows:
mMapFragment = new SupportMapFragment() {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
GoogleMap map = mMapFragment.getMap();
if (map != null) {
//Your initialization code goes here
}
}
};
Altenative approach to use Mapview inside fragment as follows:
public class Yourfragment extends Fragment {
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_fragment, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
And put map view in XML as follows:
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Here is a link to the official documentation for MapView