Search code examples
androidandroid-fragmentsandroid-nested-fragment

Google Places Auto Complete fragment causes duplicate id error


Hi I am using google's places autocomplete api in my app. I need the google places fragment in another fragment and have got it working. Basically I have a tab with 3 imagviews and when you click on one a fragment would fill the main frame layout. Initially if I click on the imagview that brings up the fragment with the autocomplete places fragment, it works. However if I go on to another tab and then back to it I get a duplicate id error on the google places autocomplete fragment.

This is the xml of the fragment that contains the autocomplete fragment:

<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:drawable/dialog_holo_light_frame"
    android:orientation="vertical">

    <fragment
        android:id="@+id/place_autocomplete_fragment"
        android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:background="@android:drawable/dialog_frame"
        tools:layout="@layout/place_autocomplete_fragment" /> 

And this is the code in the fragment that holds the autocomplete fragment:

this.locationSearchBar = (PlaceAutocompleteFragment)getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

This is the error I get :

Duplicate id 0x7f0800dc, tag null, or parent id 0x7f0800f6 with another fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment

I read the other similar questions but none of their solutions worked for me. Any help would be appreciated.


Solution

  • Try adding this code:

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mAutocompleteFragment != null && getActivity() != null && !getActivity().isFinishing()) {
            getActivity().getFragmentManager().beginTransaction().remove(mAutocompleteFragment).commit();
        }
    }
    

    You could also put this in onDestroyView() I believe. The AutocompleteFragment will need to be removed from each ACTIVITY before it is added to the same Activity. This was an issue for me when I created and later destroyed a Fragment with an AutocompleteFragment added to it and then tried to create the same Fragment again without having destroyed the Activity that it runs within.