7

I am using places api and dependency

  implementation 'com.google.android.libraries.places:places:1.0.0'

I want to add an AutocompleteSupportFragment in a fragment. Please help me where should I place the code in the fragment. I have tried on these methods

1. onCreate()
2. onCreateView()
3. onViewCreated()
4. onActivityCreated()

But it gives null object reference error. I have tried it with an activity, it works fine.

public class MyActivity extends Fragment implements OnMapReadyCallback{

    AutocompleteSupportFragment autocompleteSupportFragment;


    public ConsumerBookingMapFragment(){ }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_consumer_booking_map,container,false);
    return mView;

}

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (savedInstanceState != null) {
            mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
            mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
        }
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
        mMapView = mView.findViewById(R.id.map);
        if(mMapView != null){
            mMapView.onCreate(null);
            mMapView.onResume();
            mMapView.getMapAsync(this);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

2 Answers2

4

This is a working solution.

  AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
                    getChildFragmentManager().findFragmentById(R.id.autocomplete_fragment);

Use getChildFragmentManager() instead of getSupportFragmentManager()/getFragmentManager()

Martin Mbae
  • 1,108
  • 1
  • 16
  • 27
0

It is answered in this post...

Google Places API AutocompleteSupportFragment Null pointer Exception

Things to remember..

Make sure you use component in your layout xml file. (Not FrameLayout) Also use the android:name as shown below..

<fragment
            android:id="@+id/autoCompleteFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
        android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment" />

And follow the steps in the answer

Ramesh Guntha
  • 37
  • 1
  • 6