2011-11-24 64 views
1

我必須使用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) { 

} 
}); 

回答

1

如果創建一個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的鏈接。你真的把你的代碼,或者你只是把默認的谷歌之一在這裏的例子?如果是這樣,那就是爲什麼你不能下載它。

嘗試將鏈接放入瀏覽器,它應該仍然顯示數據,它會告訴你是否有錯誤。

0

只需將s.toString更改爲args [0] :)