Google Places API会返回INVALID_REQUEST(Android)

时间:2015-03-14 18:21:31

标签: android json google-places-api autocompletetextview api-key

我第一次在Android上使用Google Places API,因为我需要一个AutoCompleteTextView,它会在用户输入时显示位置。因此,我已经激活了Google Places API,并且我已经创建了API密钥,这是一个浏览器密钥,正如一些教程所说。当我运行应用程序并在AutoCompleteTextView上键入内容时,json文件中的状态为" INVALID_REQUEST"而且我不明白为什么。我已经阅读了类似问题的一些答案,但这对我没有帮助...
这是代码(我使用片段)

onCreateView()

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v =  inflater.inflate(R.layout.fragment_postcard_back, container, false);
        Context c = getActivity().getApplicationContext();
        AutoCompleteTextView autoCompView = (AutoCompleteTextView) v.findViewById(R.id.postcard_location_autocomplete);
        autoCompView.setAdapter(new PlacesAutoCompleteAdapter(c, R.layout.view_place_list_item));
        autoCompView.setOnItemClickListener(this);

        return v;
    }

适配器 PlacesAutoCompleteAdapter

private class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
        private ArrayList<String> resultList;

        public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
            super(context, textViewResourceId);
        }

        @Override
        public int getCount() {
            return resultList.size();
        }

        @Override
        public String getItem(int index) {
            return resultList.get(index);
        }

        @Override
        public Filter getFilter() {
            Filter filter = new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults filterResults = new FilterResults();
                    if (constraint != null) {
                        // Retrieve the autocomplete results.
                        resultList = autocomplete(constraint.toString());

                        // Assign the data to the FilterResults
                        filterResults.values = resultList;
                        filterResults.count = resultList.size();
                    }
                    return filterResults;
                }

                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    if (results != null && results.count > 0) {
                        notifyDataSetChanged();
                    }
                    else {
                        notifyDataSetInvalidated();
                    }
                }};
            return filter;
        }
    }

自动填充 方法

 private ArrayList<String> autocomplete(String input) {
        ArrayList<String> resultList = null;

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        try {
            StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
            sb.append("?key=" + API_KEY);
            sb.append("&components;=country:uk");
            sb.append("&input;=" + URLEncoder.encode(input, "utf8"));

            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Error processing Places API URL", e);
            return resultList;
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to Places API", e);
            return resultList;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        try {
            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

            // Extract the Place descriptions from the results
            resultList = new ArrayList<String>(predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {
                resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }

        return resultList;
    }

view_place_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

常数

private static final String LOG_TAG = "Google Places Autocomplete";

private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";

private static final String API_KEY = "MY KEY";

当然,&#34; MY KEY&#34;是我真正的api钥匙......

我在这里粘贴了一个屏幕截图,您可以在其中看到jsonResult

enter image description here

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

快速浏览一下,查询字符串中的;=看起来不正确。它应该只是=

如果您想使用提供GooglePlaceAutoComplete小部件的库,请查看Sprockets(我是开发人员)。使用您的API密钥进行设置后,您可以在布局中添加一个有效的Places API自动填充功能,例如:

<net.sf.sprockets.widget.GooglePlaceAutoComplete
    android:id="@+id/place"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>