Google 地方 API AutocompleteSupportFragment 空指针异常

Google Places API AutocompleteSupportFragment Null pointer Exception

我正在使用 Google Places API 获取自动完成支持片段以获取包含位置建议的搜索栏。我按照这里给出的教程 Places Autocomplete

这是XML代码

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

这是 Java 代码

// 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);
        }
    });

空指针异常出现在这一行

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

这表示 setPlaceFields 不能在空引用上调用。

首先你要初始化Places(参考here):

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

如果你想在Activity中使用AutocompleteSupportFragment,你可以这样获取:

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

如果你想在Fragment中使用AutocompleteSupportFragment,你可以这样获取:

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

我一直在与 AutoCompleteSupportFragment 作斗争。每当我点击搜索片段并开始输入时,键盘就会按下 logcat,没有任何错误。经过一番努力,我终于能够理解这个问题。如果其他人也遇到这样的问题,he/she可以试试。

地点 api、方向 api 和许多其他 gmap API 需要美元计费。如果您还没有设置您的账单或您的货币是印度卢比或任何其他货币。您需要设置新的计费方式。您可以通过在网络浏览器中调用以下 url 来验证这一点 API:https://maps.googleapis.com/maps/api/place/autocomplete/json?input=1600+Amphitheatre&key=YOUR_API_KEY

如果显示:{ "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" }

这意味着您无权访问 API,您需要设置结算 您可以访问:https://developers.google.com/maps/gmp-india-faq#bill-maps 了解如何

这里是代码

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 将地图和广告标记加载到您的当前位置和所选位置

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));
}
}

如果 Xml 中的片段 'autoCompleteFragment' 已经在另一个片段上 你应该使用

getChildFragmentManager() //Java
childFragmentManager //Kotlin

或者如果它在 activity 上使用

getSupportFragmentManager() //Java
supportFragmentManager //Kotlin