Android Google Places API - PlaceAutocompleteFragment clear button listener

前端 未结 3 812
甜味超标
甜味超标 2021-02-08 23:25

I am using Google Places API for Android - PlaceAutocompleteFragment API in my project to search locations, when user selects a location then get the records using location la

3条回答
  •  旧巷少年郎
    2021-02-08 23:29

    I create the findViewById in the onCreate of the activity, I was getting the following error

    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
    

    Because the fragment is not initialized/visible yet. I moved the listener inside the setOnPlaceSelectedListener and it's working fine now.

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            homeAddressPlaceID = place.getId();
            Log.i(TAG, "Place: " + place.getName() + ", " + place);
    
            autocompleteFragment.getView().findViewById(R.id.places_autocomplete_clear_button)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            autocompleteFragment.setText("");
                            homeAddressPlaceID = "";
                        }
                    });
        }
    
        @Override
        public void onError(Status status) {
            Log.i(TAG, "An error occurred: " + status);
        }
    });
    

提交回复
热议问题