Android how to make AutoCompleteTextView work like a Google search box

In my application, I have an Activity that extends MapActivity. and there I put a AutoCompleteTextViewbutton called "Search", so I write in AutoCompleteTextViewAnd click the "Search" button to go to this place on the Google map. AutoCompleteTextViewfor the small elements that I mention in strings.xml . But I want it to work as a Google search engine, as in the Google search box, no matter what we start writing, it automatically completes every word. The fact is that it takes data from the google server. Is not it? If so, then how can I bind data to my AutoText TextView from a Google server so that it works like a Google search box. I am using android API v2.2.

+5
source share
1 answer

You must use the Google Places API, you must first create a place API key, check this page:

http://code.google.com/apis/maps/documentation/places/

In my case, I used this code:

 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=<getyourAPIkey>");
        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) {

} });
+2
source

All Articles