Android: NullPointerException while replacing FrameLayout - android

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

Related

How to use PlaceAutoCompleteFragment widget in a Fragment

I am using PlaceAutoCompleteFragment inside a Fragment. First time when Fragment(App fragment in which PlaceAutoCompleteFragment is placed) opens it works fine like a charm.
But, then second time I hit button to open Fragment it crashes with below error. It works only a single time.
FATAL EXCEPTION:
android.view.InflateException: Binary XML file line #64: Error
inflating class fragment Caused by:
java.lang.IllegalArgumentException: Binary XML file line #64:
Duplicate id 0x7f0d0094, tag null, or parent id 0xffffffff with
another fragment for
com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
This is how I am using this,for Search location
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.parkingview_fragment, container, false);
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map_parkingview);
mapFragment.getMapAsync(this);
// For Search location
PlaceAutocompleteFragment autocompleteFragment = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_fragment_parkingview);
}
autocompleteFragment.setOnPlaceSelectedListener(this);
autocompleteFragment.setHint("Search a Location");
// autocompleteFragment.setBoundsBias(BOUNDS_MOUNTAIN_VIEW);
return view;
}
XML:
<fragment
android:id="#+id/place_fragment_parkingview"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Declare your fragment Dynamically it will solve the issue.
<FrameLayout
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
And Update your fragment onCreateView
SupportPlaceAutocompleteFragment autocompleteFragment = new SupportPlaceAutocompleteFragment();
android.support.v4.app.FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, autocompleteFragment);
ft.commit();
This problem is caused because you haven't removed yet the PlaceAutoCompleteFragment instance created before at some point.
Careful guys! If you use the method posted by Jordon, it will work, but the fragment's views (the input edittext, and the clearbutton for example) won't be accesible because the fragment's views aren't created yet...the correct answer is REMOVE the instance of the fragment putted in the xml file, programmatically, overwriting the onDestroyView method on the Fragment containing the PlaceAutoCompleteFragment.
#Override
public void onDestroyView() {
if (autocompleteFragment != null) {
android.support.v4.app.FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.remove(autocompleteFragment).commitNowAllowingStateLoss();
}
super.onDestroyView();
}
This way, anytime you recreate your Fragment it won't have an instance of the PlaceAutoCompleteFragment already created. Happy Coding!
I was using-
<fragment
android:id="#+id/location_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/plain_border"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment" />
inside my fragment layout file and initializing it using-
PlaceAutocompleteFragment locationAutocompleteFragment = (PlaceAutocompleteFragment)
getActivity().getFragmentManager()
.findFragmentById(R.id.location_autocomplete_fragment);
I switched to-
<fragment
android:id="#+id/location_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/plain_border"
android:name="com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment" />
and initialisation by-
SupportPlaceAutocompleteFragment locationAutocompleteFragment = (SupportPlaceAutocompleteFragment)
getChildFragmentManager()
.findFragmentById(R.id.location_autocomplete_fragment);

Trying to put a map in a fragment activity

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"/>

SupportMapFragment NullPointer exception

I have a frame layout in my fragment layout and I can't access map fragment after I replace the frame layout with map fragment. I am having null pointer exception when I try to access the map after I put it into frame layout.
Here's my related layout:
<FrameLayout
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="15" >
</FrameLayout>
Here's my code in fragment:
private GoogleMap map;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fm.beginTransaction()
.replace(R.id.map, SupportMapFragment.newInstance()).commit();
map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(KOCAELI, 15));
}

Android google maps loads on first open then crashes on 2nd open

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);

MapFragment inside a fragment, app crash on reopening fragment

i have a mapfragment inside another fragment
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
/>
</FrameLayout>
and im initializing map in oncreateview
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.event_fragment, null);
try{
events = new ArrayList<EventsModel>();
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
double latitude = 24.875419;
double longitude = 66.993293;
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(12).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
loadEvents().execute();
}catch(Exception e){
}
return view;
}
its working fine but when i press back button and reopen this fragment it crashes
04-19 21:18:21.803: E/AndroidRuntime(31612): Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f050006, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.MapFragment
then i googled it and put it in ondestroy
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
the above problem is resolved bu now it gives me nullpointer on reopening the fragment that had mapfragment in it may be because i removed it with above code but whats the solution now?
Please make sure that you have correctly checked the condition where map inflated is null or not while creating view for map fragment or while destroying.
put this one on onDestroy() method
SupportMapFragment mapFragment = ((SupportMapFragment)
getActivity().getSupportFragmentManager().findFragmentById(R.id.map_location_sharing));
if(mapFragment != null) {
FragmentManager fM = getFragmentManager();
fM.beginTransaction().remove(mapFragment).commit();

Categories

Resources