Search code examples
androidgoogle-places-apigoogle-places-autocomplete

Google Places API AutocompleteSupportFragment Null pointer Exception


I am using the Google Places API to get an autocomplete support fragment to get a search bar with location suggestions. I followed the tutorial given here Places Autocomplete

This is the XML code

<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 this is the Java code

// Initialize the AutocompleteSupportFragment.
    AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.autoCompleteFragment);

    // Specify the types of place data to return.
    autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

        // Set up a PlaceSelectionListener to handle the response.
    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
        }
        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            Log.i(TAG, "An error occurred: " + status);
        }
    });

The null pointer exception comes on this line

autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

Which says that setPlaceFields cannot be called on a null reference.


Solution

  • First of all, you have to initialize Places (reference here):

    // Add an import statement for the client library.
    import com.google.android.libraries.places.api.Places;
    // Initialize Places.
    Places.initialize(getApplicationContext(), apiKey);
    

    If you want to use the AutocompleteSupportFragment inside an Activity, you can get it in this way:

    AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
        getSupportFragmentManager().findFragmentById(R.id.autoCompleteFragment);
    

    If you want to use the AutocompleteSupportFragment inside a Fragment, you can get it in this way:

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