AutoCompleteTextView使用Google Place API无法正常工作
问题描述:
我必须使用Google Places API创建AutoCompleteTextView
。我尝试了以下代码,但它不起作用。我没有收到任何错误,也无法获得Google搜索框等任何建议。AutoCompleteTextView使用Google Place API无法正常工作
请建议如何做到这一点或我要出错的地方。
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count%3 == 1) {
adapter.clear();
try {
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(s.toString(), "UTF-8") +"&types=geocode&language=fr&sensor=true&key=<getyourowndamnkey>");
URLConnection tc = googlePlaces.openConnection();
Log.d("GottaGo", URLEncoder.encode(s.toString()));
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
while ((line = in.readLine()) != null) {
sb.append(line);
}
JSONObject predictions = new JSONObject(sb.toString());
JSONArray ja = new JSONArray(predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
adapter.add(jo.getString("description"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
答
如果创建一个logcat的消息,像一个你有GottaGo,其中包括从Places API的一些预期的结果,这可以帮助你检查数据,看看那里的问题所在。
https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(s.toString(), "UTF-8") +"&types=geocode&language=fr&sensor=true&key=<getyourowndamnkey>
这是您尝试连接到URL的链接。你真的把你的代码,或者你只是把默认的谷歌之一在这里的例子?如果是这样,那就是为什么你不能下载它。
尝试将链接放入浏览器,它应该仍然显示数据,它会告诉你是否有错误。
答
只需将s.toString更改为args [0] :)