Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 571
Neeraj Athalye Avatar asked Mar 14 '19 19:03

Neeraj Athalye


2 Answers

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);
like image 93
A M Avatar answered Oct 22 '22 08:10

A M


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));
}
}
like image 27
mohit48 Avatar answered Oct 22 '22 07:10

mohit48