I'm having an issue with my Android app. I'm using navigation drawer with onCreateView() inside of a PlaceholderFragment like this:
// Google Map
private GoogleMap map;
private final LatLng LOCATION_DEPAUW = new LatLng(39.640343, -86.860687);
public static class PlaceholderFragment extends Fragment {
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#SuppressWarnings("unused")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
...
else if(mTitle.equals("Map")){
Log.d("Map", "Worked");
rootView = inflater.inflate(R.layout.google_map, container, false);
try {
if (map == null) {
SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
}
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_DEPAUW, 15);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomGesturesEnabled(true);
map.getUiSettings().setCompassEnabled(true);
map.getUiSettings().setRotateGesturesEnabled(true);
map.animateCamera(update);
/*
* for different colors:
* googlemap.addMarker(new MarkerOptions().position(new LatLng( 65.07213,-2.109375)).title("This is my title").snippet("and snippet").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
*
* .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE) is the key. change the HUE_ORANGE to anything that is available
*
*/
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
I have already imported everything correctly and the map initializes correctly on the first view. The problem is when I navigate to another fragment and then go back to this map fragment, my app crashes. I've tried to use an eclipse emulator but couldnt get it configured correctly. Does anyone know a way to handle the life cycle of a map inside a placeholderfragment? Thanks!
So after a lot of research, I found out someone manage to handle this well.
Check out this github repository:
https://gist.github.com/joshdholtz/4522551
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, 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);
// 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();
}
initially though, I had issues cause I had multiple fragments to switch between, so i did this in mine:
public void onResume() {
try{
super.onResume();
mapView.onResume();
}catch(NullPointerException e){
Log.d("onResume", "NullPointerException: " + e);
}
}
#Override
public void onDestroy() {
try{
super.onDestroy();
mapView.onDestroy();
}catch(NullPointerException e){
Log.d("onDestroy", "NullPointerException: " + e);
}
}
#Override
public void onLowMemory() {
try{
super.onLowMemory();
mapView.onLowMemory();
}catch(NullPointerException e){
Log.d("onLowMemory", "NullPointerException: " + e);
}
}
Related
So, I basically put a GoogleMaps API inside a fragment in my app, and I want to give it a specific default search like we do with Intent, but in this case im using fragment instead of an intent.`public class LocalGymsFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_local_gyms, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}`
I suggest that you try implementing the GoogleMaps API on a constraint layout or new GoogleMaps Activity. This is because Fragments aren't just a cup of tea. It is tough implementing this on fragments.
Title can be a bit complicated but the problem is literally as described. I'm trying to use google map fragment within a fragment stack. When the application starts the user will see a button and when the user pushes the button, current view will be replaced with map fragment. Currently, I'm able to replace the fragments but when the map fragment is shown, the view still has the button of previous fragment.Also I'm trying to replace fragments in one of the tabs of my app. Here is my code;
Map Fragment;
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_maps, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
try {
googleMap.setMyLocationEnabled(true);
} catch (SecurityException e) {
e.printStackTrace();
}
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Home Fragment;
public class HomeFragment extends RootFragment {
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Obtain the shared Tracker instance.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_tab, container, false);
Button go = (Button)v.findViewById(R.id.btn_go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent = new Intent(getActivity(), MapFragment.class);
//startActivity(intent);
enterNextFragment();
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
private void enterNextFragment() {
// Pushing MapView Fragment
Fragment fragment = Fragment.instantiate(this.getContext(), MapFragment.class.getName());
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_mainLayout, fragment);
ft.commit();
}
}
Map Layout;
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Home Fragment;
<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=".HomeFragment"
android:background="#android:color/white"
android:id="#+id/fragment_mainLayout">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_go"
android:layout_width="fill_parent"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content"
android:layout_marginTop="170dp"
android:text="GO"/>
</FrameLayout>
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
Your fragments shouldn't communicate directly according to the documentation.
If you've managed to communicate with your fragments considering the documentation. Then you can use this simple method to be able to change and reuse any fragment.
In your host activity :
private void changeFragment(Fragment frag, boolean saveInBackstack) {
String backStateName = ((Object) frag).getClass().getName();
try {
FragmentManager manager = getSupportFragmentManager();
if (manager.findFragmentByTag(backStateName) == null) {
//fragment not in back stack, create it.
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, frag, backStateName);
if (saveInBackstack) {
Log.d(TAG, "Change Fragment: addToBackTack " + backStateName);
transaction.addToBackStack(backStateName);
} else {
Log.d(TAG, "Change Fragment: NO addToBackTack");
}
transaction.commit();
} else {
manager.popBackStack();
}
} catch (IllegalStateException exception) {
Log.w(TAG, "Unable to commit fragment, could be activity as been killed in
}
}
just add android:background="#android:color/white" on the main view of the map_layout xml file
Here is the solution;
Home Fragment;
public class HomeFragment extends RootFragment {
private LocationManager locationManager;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Obtain the shared Tracker instance.
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_tab, container, false);
Button go = (Button) v.findViewById(R.id.btn_go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MapFragment.class);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//Toast.makeText(getContext(), "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
}
MapFragment (it is now fragmentActivity not fragment);
public class MapFragment extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
MapView mMapView;
private GoogleMap googleMap;
// private GoogleMap map;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private Marker marker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(this.getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = null;
try {
googleMap.setMyLocationEnabled(true);
location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
} catch (SecurityException e) {
e.printStackTrace();
}
if (location != null) {
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
I'm using the solution here to add markers to a map in a Fragment and can't figure out why I can only add one marker.
I'm sure I'm missing something when I build the camera position, which is getting called twice in my test code. (See addLocationToMap below).
I am retrieving an ArrayList of geocoordinates on the main thread and want to loop through the list in the map tab calling addLocationToMap on each entry.
Here's my code:
public class RentalMapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate and return the layout
View v = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) v.findViewById(R.id.mapView);
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();
int level = 12;
addLocationToMap(17.385044, 78.486679, "Marker 2", level);
addLocationToMap(17.385044, 78.486671, "Marker 1", level);
// Perform any camera updates here
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(17.385000, 78.486600)).zoom(level).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
return v;
}
private void addLocationToMap(double latitude, double longitude, String markerTitle, int level) {
// Create lat/lon
LatLng latLng = new LatLng(latitude, longitude);
// create marker
MarkerOptions marker = new MarkerOptions().position(latLng).title(markerTitle);
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
It turns out that I should not be creating the camera position after placing each marker. Rather, after adding all my markers I need to choose a postion for the camera to view the markers from.
I'm updating my question to demonstrate this.
I have two FrameLayout in an activity, I just replace fragments inside those FrameLayout.
It works great with everyfragment BUT the one containing the MapFragment for the GoogleMap.
When I first launch the app it works and I see the map (everything works) but when I replace the fragment and replace it back I just get a blank space like nothing is loaded.
public class MapFragment extends CustomFragment {
private GoogleMap mMap;
private Marker currentMarker;
private OnFragmentInteractionListener mListener;
public static final String ID = "MAP_FRAGMENT";
private static View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
try {
view = inflater.inflate(R.layout.fragment_map, container, false);
} catch (InflateException e) {
Log.d("","");
}finally{
setUpMapIfNeeded();
if(view!=null)this.view=view;
return this.view;
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = getFragmentManager().findFragmentById(R.id.map);
if (f != null)getActivity().getFragmentManager().beginTransaction().remove(f).commit();
mMap=null;
currentMarker=null;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
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 = ((com.google.android.gms.maps.MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void update(FragmentMessage message) {
if(mMap!=null) {
Location loc = (Location) message.getMessages()[0];
if (currentMarker != null)
currentMarker.remove();
currentMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(loc.getLatitude(), loc.getLongitude())).title("Marker"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(loc.getLatitude(), loc.getLongitude())) // Sets the center of the map to Mountain View
.zoom(15) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
The mMap is never null, so the MapFragment is working I guess but I don't get anything on the screen (see screenshots below).
Does anyone have an idea ? I really don't know what is wrong.
I'm really having a hard time figuring this out. When I looked where the logcat points the error, it points to this line:
throw new RuntimeException(i);
inside this
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException i) {
throw new RuntimeException(i);
} catch (IllegalAccessException i) {
throw new RuntimeException(i);
}
}
This happens when I changed to landscape orientation. I know the view is being recreated after a change of orientation, I was able to do this on my Google maps also in this app, but I don't know how to implement it on a webview. I have a webview that shows facebook sharer.php and when I change it to landscape orientation, it force stops.
This is my code for this tab:
public class TabFour extends Fragment {
static WebView webView;
String myBlogAddr = "http://192.168.1.75/Treasuria-v2/";
String myUrl;
Button map;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_tab_four, container, false);
displayWebview();
return rootView;
}
protected void displayWebview(){
webView= (WebView)rootView.findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
String title = "Quezon City Guide";
String desc = "Your Number One City Guide!";
String image = "http://s22.postimg.org/5t4qidqpt/launcher114x114.png";
myBlogAddr ="http://www.facebook.com/sharer.php?m2w&s=100&p[title]="+title+"&p[summary]="+desc+"&p[url]=http://www.sample.com&p[images][0]="+image;
if(myUrl == null){
myUrl = myBlogAddr;
}
webView.loadUrl(myUrl);
Log.i("URL", myBlogAddr);
map = (Button) rootView.findViewById(R.id.buttonMap);
map.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getActionBar().setSelectedNavigationItem(2);
}
});
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
myUrl = url;
view.loadUrl(url);
return true;
}
}
public void onBackPressed() {
if(webView.canGoBack())
webView.goBack();
}
public void OnCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getActivity().getActionBar().setSelectedNavigationItem(1);
map = (Button) rootView.findViewById(R.id.buttonMap);
map.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getActionBar().setSelectedNavigationItem(2);
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException i) {
throw new RuntimeException(i);
} catch (IllegalAccessException i) {
throw new RuntimeException(i);
}
}
}
GoogleMap Tab
public class TabTwo extends Fragment {
private static View view;
private static GoogleMap map;
private static Double latitude, longitude;
private static LatLngBounds QC = new LatLngBounds(
new LatLng(14.656669, 120.998598), new LatLng(14.666965, 121.098934));
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_tab_two, null);
// Passing hard coded values for latitude & longitude. Please change as per your need. This is just used to drop a Marker on the Map
latitude = 14.6353475;
longitude = 121.0327501;
map = ((SupportMapFragment) MainActivity.fragmentManager
.findFragmentById(R.id.map)).getMap();
setUpMapIfNeeded(); // For setting up the MapFragment
return view;
}
/***** Sets up the map if it is possible to do so *****/
public static void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) MainActivity.fragmentManager
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (map != null)
setUpMap();
}
}
/**
* This is where we can add markers or lines, add listeners or move the
* camera.
* <p>
* This should only be called once and when we are sure that {#link #mMap}
* is not null.
*/
private static void setUpMap() {
// For showing a move to my location button
map = ((SupportMapFragment) MainActivity.fragmentManager
.findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.getUiSettings().setCompassEnabled(true);
map.getUiSettings().setRotateGesturesEnabled(true);
// For dropping a marker at a point on the Map
map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Estuar Building").snippet("Work Place"));
// For zooming automatically to the Dropped PIN Location
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 12.0f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(QC.getCenter(), 12));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (map != null)
setUpMap();
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) MainActivity.fragmentManager
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (map != null)
setUpMap();
}
}
/**** The mapfragment's id must be removed from the FragmentManager
**** or else if the same it is passed on the next time then
**** application will crash ****/
#Override
public void onDestroyView() {
super.onDestroyView();
try {
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
setUpMap();
} catch (Exception e) {
e.printStackTrace();
}
}
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException i) {
throw new RuntimeException(i);
} catch (IllegalAccessException i) {
throw new RuntimeException(i);
}
}
}
Please help. Thanks!
try this...
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException i) {
}
catch (IllegalAccessException i) {
}
}