Google位置API自动完成置换式null指针异常



我正在使用Google Places API获取自动完成支持片段,以获取带有位置建议的搜索栏。我遵循此处提供的教程位置自动完成

这是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无法通过null引用调用。

首先,您必须初始化位置(请参考):

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

如果您想在活动中使用自动完整的PpportFragment,则可以通过这种方式获得:

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

如果要在片段内使用自动完整的PpportFragment,则可以以这种方式获取它:

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

我在自动完成范围内挣扎。每当我敲击搜索片段并开始键入时,键盘就会下降,而logcat中没有任何错误。经过很多挣扎,我终于能够理解这个问题。如果其他人也面临着这个问题,他/她可以尝试。

放置API,Direction API和许多其他GMAP API都需要US $计费。如果您尚未设置帐单或您的货币为INR或任何其他货币。您需要设置一种新的计费方法。您可以通过在Web浏览器中调用plote api的关注url来验证此验证:https://maps.googleapis.com/maps/api/place/autocomplete/json?input=1600 amphitheAmpHitheTre&amk;

如果显示:{ " error_message":"您必须在https://console.cloud.google.com/projecn/project/_/billing/enable/Enable在https://developers.google.com/maps/maps/gmp/gmp上了解更多信息 - 启动", "地方":[], "状态":" 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>

mapActivity.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

或在活动中使用的地方

getSupportFragmentManager() //Java
supportFragmentManager //Kotlin

最新更新