【问题标题】:Google Places autocomplete Android - Not workingGoogle 地方信息自动填充 Android - 不工作
【发布时间】:2015-07-13 15:59:54
【问题描述】:

我是 Android 应用开发的新手。 我跟着this toturial 写了一个简单的Google Places 自动完成Android 应用程序,但是当我开始输入应用程序时它没有返回任何建议;当我在自动完成文本视图中编写任何内容时,它会在 LogCat 中出现 NativeCrypto 错误。这是我的代码:

package com.example.newxyz; 

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;

public class GooglePlacesAutocompleteActivity extends Activity implements OnItemClickListener {
    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 = "AIzaSyAujQlZ1Jj64NAHMoynXjI253MVRzGW09w";
    private static final String True = "true";
    private static final String language = "en";

    AutoCompleteTextView autoCompView;
    @Override

   public void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);

        autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));

        autoCompView.setOnItemClickListener(this);

    } 



    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

        String str = (String) adapterView.getItemAtPosition(position);
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
   }

    public static 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("?sensor=" + True);
            sb.append("&key=" + API_KEY);
            sb.append("&language" + language);
            //sb.append("&components=country:gr");
            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++) {
                System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
                System.out.println("============================================================");
                resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
     }
        return resultList;
    }
   class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
        private ArrayList<String> resultList;
        public GooglePlacesAutocompleteAdapter(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;
       }
    }
}

这是我的 LogCat 错误:

05-04 13:16:27.705: E/NativeCrypto(9312): ssl=0x611c0a20 cert_verify_callback x509_store_ctx=0x62625940 arg=0x0
05-04 13:16:27.705: E/NativeCrypto(9312): ssl=0x611c0a20 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
  • 我已在 console.developers.google.com 中启用了适用于 Android 的 Google Places API
  • 我正在为我的应用程序使用浏览器键
  • 我已寻找问题的答案,但尚未找到任何相关答案
  • 我已在 Menifest 文件中授予 Internet 权限
  • 在开发者控制台概览中,图表显示请求,这意味着已发出请求但没有响应。

任何帮助将不胜感激。 谢谢

【问题讨论】:

  • “它在 LogCat 中给出 NativeCrypto 错误”?然后请发布 dat logcat(记录器实际上有助于调试)...
  • 请查看已编辑的帖子
  • 可能值得看看支持自动完成功能的新 Places API for Android (developers.google.com/places/android)。
  • @plexer 我重新检查并按照您提供的链接中的每个步骤进行操作...错误仍然存​​在
  • 您提到您正在使用浏览器键。您是否将其更改为 Android 密钥?

标签: android api autocomplete google-places-api


【解决方案1】:

请尝试这样做:

final StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
final URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
final InputStreamReader in = new InputStreamReader(conn.getInputStream());

它在我的情况下工作。

【讨论】:

  • 实际问题出在您的 API 密钥中。当我用我的代码尝试它时不起作用。但使用我的 API 密钥,它可以正常工作。
  • @HasmukhBarochiya 请在您的答案中提供一些解释,并尽可能避免仅使用代码的答案(在这种情况下,您怀疑是通用代码或 API 密钥)。
  • @shkschneider 感谢您的建议。下次我会这样做。我只想说 API 密钥在这种情况下不起作用,我在我的应用程序中使用相同的代码,并且它与我的 API 密钥一起工作正常(我使用多个密钥进行测试),但提供的密钥有问题不工作。
  • @Hasmukh Barochiya 你能告诉我如何处理 API 密钥吗?我在 console.developers.google.com 中删除了我的项目创建了一个新项目,创建了新密钥,但它仍然无法正常工作......
【解决方案2】:

由于您使用的是 Places API 网络服务(而不是 Android 服务),因此您必须在 Google Developers Console 中启用 Google Places API Web Service API。

一旦你完成了这项工作,如果你想简化你的代码并使用一个提供GooglePlaceAutoComplete 小部件的库,请查看Sprockets(我是开发人员)。使用您的 API 密钥进行设置后,您可以在布局中添加一个可以工作的 Places API 自动完成功能,如下所示:

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

【讨论】:

  • 如果我的 API 密钥不起作用,库有什么用?
  • 看来您只需要启用另一个 API。我已将详细信息添加到答案中。
  • 我为 android 制作了一个密钥,并为 Android 启用了 Google Places API,但同样的错误。
【解决方案3】:

我昨天正在解决这个问题,所以它要么

  • 错误的API_KEY(例如,您可能在 build.gradle 中设置了不同的前缀来调试版本,或者使用了错误的 SH1 或注册到其他的而不是“Google Places API for Android”)
  • 如果您的 GoogleApiClient 未使用 enableAutoManage(fragmentActivity, clientId, connectionCallback) 构建,则调用 GoogleApiClient.blockingConnect()GoogleApiClient.connect()

坦率地说,我对#Google 如何完成此 API 感到不满意。太奇怪了,如果你得到代码 9001、9006、9007 什么的,如何理解发生了什么?

【讨论】:

  • 我正在尝试删除并制作新的 API_KEY,SH1 适用于 Google 地图,但不适用于 Google 地点。 Google Places API for Android 是我注册的……我不明白你的第二点。你能详细说明一下吗
  • 哎呀,我才意识到我回答错了问题。我说的是来自 google play services for Android 的 Google Places 的东西。但是您可能有兴趣查看此developers.google.com/places/android/autocomplete
  • 这个 API 并不是真的要被使用就是为什么,并且正在关闭。看这里:venturebeat.com/2015/07/24/…
【解决方案4】:

就我而言,问题是

"status":"REQUEST_DENIED",
"error_message":"This API project is not authorized to use this API. Please ensure that this API is activated "

解决方案是在 Google Api 控制台中启用 Google Places API Web Service

【讨论】:

    【解决方案5】:

    我喜欢一个解决方案,文本观察器没有任何问题。

    在下面的代码中,我没有覆盖“performFiltering”方法。我添加了它,我的自动完成文本框现在工作正常。

    public class CustomAutoCompleteView extends AutoCompleteTextView {  
    
    public CustomAutoCompleteView(Context context) {  
        super(context);  
        // TODO Auto-generated constructor stub  
    }  
    
    public CustomAutoCompleteView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        // TODO Auto-generated constructor stub  
    }  
    
    public CustomAutoCompleteView(Context context, AttributeSet attrs,  
            int defStyle) {  
        super(context, attrs, defStyle);  
        // TODO Auto-generated constructor stub  
    }  
    
    @Override  
    protected void performFiltering(final CharSequence text, final int keyCode) {  
        String filterText = "";  
        super.performFiltering(filterText, keyCode);  
    }  
    /** 
    * After a selection, capture the new value and append to the existing 
    * text 
    */  
    @Override  
    protected void replaceText(final CharSequence text) {  
        super.replaceText(text);  
    }  
    
    }  
    

    【讨论】:

      【解决方案6】:

      启用“Google Places API Web 服务”API 并试一试。它对我有用。

      【讨论】:

        【解决方案7】:

        转到Google Console >> Api >> 启用 Google Places API Web 服务。 见Solution

        【讨论】:

          【解决方案8】:

          解决方案是将 googlePlaceApi 添加到 console.developers.google.com 中的项目

          【讨论】:

            猜你喜欢
            • 2012-04-27
            • 2014-03-28
            • 2015-06-15
            • 1970-01-01
            • 2016-08-28
            • 1970-01-01
            • 1970-01-01
            • 2020-08-04
            • 1970-01-01
            相关资源
            最近更新 更多