8

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.

Neeraj Athalye
  • 508
  • 5
  • 26

3 Answers3

16

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);
A M
  • 831
  • 1
  • 14
  • 26
  • I am not getting a null pointer exception anymore but now if I click on the autocomplete support fragment and then click somewhere else on the screen, I am unable to click on the autocomplete support fragment and the logcat shows this error `Autocomplete activity cannot be launched until fragment is enabled.` – Neeraj Athalye Mar 18 '19 at 18:41
  • 5
    I fixed this error as well by calling `super.onActivityResult(requestCode, resultCode, data);` – Neeraj Athalye Mar 18 '19 at 19:08
  • clicking on map twice creates an error: Binary XML file line #1: Duplicate id 0x7f080043, tag null, or parent id 0x1020002 with another fragment for com.google.android.libraries.places.widget.AutocompleteSupportFragment – user3560827 Jun 06 '22 at 16:39
2

I was struggling with AutoCompleteSupportFragment. Whenever I was tapping on the search fragment and started typing, the keyboard just went down without any error in logcat. After a lot of struggle i was finally able to understand the problem. If anyone else is also facing such issue, he/she can try.

places api, direction api and many other gmaps APIs need US$ billing. If you haven't setup you billing or your currency is in INR or any other currency. You need to setup a new billing method. You can verify this by calling following url in your web browser for places API: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=1600+Amphitheatre&key=YOUR_API_KEY

if it shows: { "error_message" : "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started", "places" : [], "status" : "REQUEST_DENIED" }

that means you dont have access to API and you need to setup your billing you can visit: https://developers.google.com/maps/gmp-india-faq#bill-maps to learn how

and here is the code if you want

activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
android:orientation="vertical"
android:weightSum="1">
<fragment android:id="@+id/autocomplete_fragment"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment" />
<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    map:uiZoomGestures="true"/>
</LinearLayout>

MapsActivity.java to load maps and ad marker to your current place and selected place

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    if (!Places.isInitialized()) {
        Places.initialize(getApplicationContext(), getString(R.string.api_key));
    }
    PlacesClient placesClient = Places.createClient(this);
    //AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();

    // Initialize the AutocompleteSupportFragment.

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

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

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

    // 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.
            LatLng dest = place.getLatLng();
            mMap.addMarker(new MarkerOptions().position(dest).title("Destination"));
            //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);
        }
    });
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;


    //getting current location
    // Add a marker in Sydney and move the camera
    LatLng currentlocation = new LatLng(LocationService.lat, LocationService.lon);//change LocationService.lat and LocationService.lon with your current latitude and logitude that you have calculated
    mMap.addMarker(new MarkerOptions().position(currentlocation).title("Your Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentlocation));
}
}
mohit48
  • 712
  • 7
  • 9
2

if your fragment 'autoCompleteFragment' in Xml is already on another fragment you should use

getChildFragmentManager() //Java
childFragmentManager //Kotlin

or if it where on an activity use

getSupportFragmentManager() //Java
supportFragmentManager //Kotlin