Google API 已连接,但在 android 中提出了未针对 AutoCompleteTextView 提出的建议

Google API connected but place sugesstions not giving for AutoCompleteTextView in android

大家好, 我们面临一个关于 google 地图的问题,即使用 AutoCompleteTextview 查找地点。 我们收到 Google API 已连接的消息,但 AutoCompleteTextView 没有显示地点,即没有给出任何地点建议

下面是代码:

  public class PlacesAutoCompleteActivity extends BaseActivity implements
        GoogleApiClient.OnConnectionFailedListener,
        GoogleApiClient.ConnectionCallbacks {
    private static final String LOG_TAG = "Finding Location";
    private static final int GOOGLE_API_CLIENT_ID = 0;
    private static final int ACCESS_FINE_LOCATION = 0;
    private AutoCompleteTextView mAutocompleteTextView;
    private GoogleApiClient mGoogleApiClient;
    private PlaceArrayAdapter mPlaceArrayAdapter;
    private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
            new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
    private Toolbar mToolbar;
    private TextView tv_currentLocation;
    Context mContext;
    public static double latitude = 0;
    public static double longitude = 0;
    Handler handler;
    public static String st_city, st_postalcode, st_statename, st_countryname;
    private String str_loc = null;
    private ListView lv_location;

    ArrayList<String> arraylocation;
    List<Addressdetails> address_details;
    ArrayAdapter<String> locationadapter;

    private LinearLayout ll_currentlocation;
    private String st_featurName;
    private String st_throughfare;
    private String st_loc_firstname;
    private String st_loc_lastname;
    private String st_loc_email;
    private String st_loc_phone;
    private String st_loc_specailInstrc;
    private String st_loc_addressline2;
    private String st_loc_active;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pick_up_location);
        mContext = this;
        mToolbar = (Toolbar) findViewById(R.id.toolbar_picklocation);
        setSupportActionBar(mToolbar);
        //  mToolbar.setTitle(R.string.app_name);
        mToolbar.setTitleTextColor(getResources().getColor(R.color.white));
        mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });




        if (InternetDetector.isConnected(PlacesAutoCompleteActivity.this)) {

            mGoogleApiClient = new GoogleApiClient.Builder(PlacesAutoCompleteActivity.this)
                    .addApi(Places.GEO_DATA_API)
                    .enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
                    .addConnectionCallbacks(this)
                    .addApi(LocationServices.API)
                    .addApi(Places.PLACE_DETECTION_API)
                    .addOnConnectionFailedListener(this)
                    .build();


            mAutocompleteTextView = (AutoCompleteTextView) findViewById(R.id.autocomplete_places);
            mAutocompleteTextView.setThreshold(1);
            mAutocompleteTextView.setDropDownBackgroundResource(R.color.white);
            mAutocompleteTextView.setOnItemClickListener(mAutocompleteClickListener);
            mPlaceArrayAdapter = new PlaceArrayAdapter(this, android.R.layout.simple_list_item_1, BOUNDS_MOUNTAIN_VIEW, null);
            mAutocompleteTextView.setAdapter(mPlaceArrayAdapter);




    }


    private String loc_placename;
    private AdapterView.OnItemClickListener mAutocompleteClickListener
            = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final PlaceArrayAdapter.PlaceAutocomplete item = mPlaceArrayAdapter.getItem(position);
            final String placeId = String.valueOf(item.placeId);

            loc_placename = String.valueOf(item.description);

            Log.i(LOG_TAG, "Loctaionname " + loc_placename);


            PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
                    .getPlaceById(mGoogleApiClient, placeId);
            placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
            Log.i(LOG_TAG, "Fetching details for ID: " + item.placeId);
        }
    };


    private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
            = new ResultCallback<PlaceBuffer>() {
        @Override
        public void onResult(PlaceBuffer places) {

            if (!places.getStatus().isSuccess()) {
                Log.d(LOG_TAG, "Place query did not complete. Error: " +
                        places.getStatus().toString());
                return;
            }
            // Selecting the first object buffer.
            try {

                final Place place = places.get(0);

                // CharSequence attributions = places.getAttributions();
                LatLng queried_location = place.getLatLng();

                latitude = queried_location.latitude;
                longitude = queried_location.longitude;
                //Toast.makeText(getApplicationContext(),queried_location.latitude+ "Text"+queried_location.longitude, Toast.LENGTH_LONG).show();
                getAddressFromLocation(latitude, longitude, getApplicationContext(), handler);


                    //
                }

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }
    };


    public void getAddressFromLocation(final double latitude, final double longitude,
                                       final Context context, final Handler handler) {
        Thread thread = new Thread() {

            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String result = null;
                try {
                    List<Address> addressList = geocoder.getFromLocation(
                            latitude, longitude, 1);

                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        st_city = address.getLocality();
                        st_countryname = address.getCountryName();
                        st_postalcode = address.getPostalCode();
                        st_statename = address.getAdminArea();
                        st_featurName = address.getFeatureName();//route
                        st_throughfare = address.getThoroughfare();//street
                        Log.d("values", st_featurName + st_throughfare);
                    }
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Unable connect to Geocoder", e);
                }
            }
        };
        thread.start();
    }



    }

    @Override
    public void onConnected(Bundle bundle) {
        mPlaceArrayAdapter.setGoogleApiClient(mGoogleApiClient);
        Log.i(LOG_TAG, "Google Places API connected.");

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(LOG_TAG, "Google Places API connection failed with error code: "
                + connectionResult.getErrorCode());

 /*       Toast.makeText(this,
                "Google Places API connection failed with error code:" +
                        connectionResult.getErrorCode(),
                Toast.LENGTH_LONG).show()*/;
    }

    @Override
    public void onConnectionSuspended(int i) {
        mPlaceArrayAdapter.setGoogleApiClient(null);
        Log.e(LOG_TAG, "Google Places API connection suspended.");
    }

}

这是 PlaceAdapter class:

package com.app.letmecall.customer.Adapters;

import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLngBounds;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("unchecked")
public class PlaceArrayAdapter

        extends ArrayAdapter<PlaceArrayAdapter.PlaceAutocomplete> implements Filterable {
    private static final String TAG = "PlaceArrayAdapter";
    private GoogleApiClient mGoogleApiClient;
    private AutocompleteFilter mPlaceFilter;
    private LatLngBounds mBounds;
    private ArrayList<PlaceAutocomplete> mResultList;

    /**
     * Constructor
     *
     * @param context  Context
     * @param resource Layout resource
     * @param bounds   Used to specify the search bounds
     * @param filter   Used to specify place types
     */
    @SuppressWarnings("unchecked")
    public PlaceArrayAdapter(Context context, int resource, LatLngBounds bounds,
                             AutocompleteFilter filter) {
        super(context, resource);
        mBounds = bounds;
        mPlaceFilter = filter;
    }
    @SuppressWarnings("unchecked")
    public void setGoogleApiClient(GoogleApiClient googleApiClient) {
        if (googleApiClient == null || !googleApiClient.isConnected()) {
            mGoogleApiClient = null;
        } else {
            mGoogleApiClient = googleApiClient;
        }
    }
    @SuppressWarnings("unchecked")
    @Override
    public int getCount() {
        return mResultList.size();
    }
    @SuppressWarnings("unchecked")
    @Override
    public PlaceAutocomplete getItem(int position) {
        return mResultList.get(position);
    }
    @SuppressWarnings("unchecked")
    private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) {
        if (mGoogleApiClient != null) {
            Log.i(TAG, "Executing autocomplete query for: " + constraint);
            PendingResult<AutocompletePredictionBuffer> results =
                    Places.GeoDataApi
                            .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                    mBounds, mPlaceFilter);
            // Wait for predictions, set the timeout.
            AutocompletePredictionBuffer autocompletePredictions = results
                    .await(60, TimeUnit.SECONDS);
            final Status status = autocompletePredictions.getStatus();
            if (!status.isSuccess()) {
               /* Toast.makeText(getContext(), "Error: " + status.toString(),
                        Toast.LENGTH_SHORT).show();
                Log.e(TAG, "Error getting place predictions: " + status
                        .toString());*/
                autocompletePredictions.release();
                return null;
            }

            Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
                    + " predictions.");
            Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
            ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
            while (iterator.hasNext()) {
                AutocompletePrediction prediction = iterator.next();
                resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
                        prediction.getDescription()));
            }
            // Buffer release
            autocompletePredictions.release();
            return resultList;
        }
        Log.e(TAG, "Google API client is not connected.");
        return null;
    }
    @SuppressWarnings("unchecked")
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint != null) {
                    // Query the autocomplete API for the entered constraint
                    mResultList = getPredictions(constraint);
                    if (mResultList != null) {
                        // Results
                        results.values = mResultList;
                        results.count = mResultList.size();
                    }
                }
                return results;
            }
            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    // The API returned at least one result, update the data.
                    notifyDataSetChanged();
                } else {
                    // The API did not return any results, invalidate the data set.
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }
    @SuppressWarnings("unchecked")
    public class PlaceAutocomplete {

        public CharSequence placeId;
        public CharSequence description;
        @SuppressWarnings("unchecked")
        PlaceAutocomplete(CharSequence placeId, CharSequence description) {
            this.placeId = placeId;
            this.description = description;
        }
        @SuppressWarnings("unchecked")
        @Override
        public String toString() {
            return description.toString();
        }
    }
}

请指导! 提前致谢

试试这个

((TextView) findViewById(R.id.startpoint)).setOnClickListener(this);

OnClick(View)

里面
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN).build(Final_maps.this);
                startActivityForResult(intent, REQUEST_INT);

Select地点:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Place place = PlaceAutocomplete.getPlace(Final_maps.this, data);
Log.d(TAG, place.toString());
((TextView) findViewById(R.id.startpoint)).setText(place.getName());

确保在清单中添加了

<permission
    android:name="<com.package.name>.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="<com.package.name>.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />