2

As an user is typing in an AutoCompleteTextView, I want to get some results from an webservice and display them in the box.

For this I declared globally

ArrayAdapter<String> adapter;
autoCompleteText;
ArrayList<String> searchList;

I put this in my onCreate(). searchList is an ArrayList where I will get the results from the web service. Search() is my webservice search. I want it to search after the user typed at least 3 chars so that I used a TextWatcher on the field.

    adapter = new ArrayAdapter<String>(MyActivity.this
            , android.R.layout.simple_list_item_1, searchList);
    autoCompleteText.setAdapter(adapter);
    autoCompleteText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            if (s.length() >= 3) {
                new Search().execute(null, null, null);
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

Method from Search() - GET request in AsyncTask where I update my searchList

@Override
    protected void onPostExecute(final Void unused) {
        dlg.dismiss();
        if (result != null) {
            try {
                JSONObject myJson = new JSONObject(result.substring(4));

                JSONObject resp = myJson.getJSONObject("response");
                for (Iterator<String> iterator = resp.keys(); iterator.hasNext();) {
                    String key = iterator.next();
                    System.out.println(key + " = " + resp.getString(key));
                    if(! searchList.contains(resp.getString(key)))
                        searchList.add(resp.getString(key));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }
}

I would prefer to use ArrayAdapter and not a CustomAdapter. Any ideas?

Gabi Rotaru
  • 115
  • 1
  • 8

2 Answers2

0

Try calling notifyDataSetChanged() in onPostExecute() after changing the list.

thuongnh.uit
  • 161
  • 6
0

This is how I update my AutoCompleteTextView:

String[] data = terms.toArray(new String[terms.size()]);  
// terms is a List<String>
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(activity, android.R.layout.simple_dropdown_item_1line, data);
keywordField.setAdapter(adapter);  // keywordField is a AutoCompleteTextView
if(terms.size() < 40) keywordField.setThreshold(1); 
else keywordField.setThreshold(2);

Now of course, this is static and doesn't deal with an over-the-air suggestions but, I can also suggest you to notify adapter for the changes after you assign it to the AutoCompleteTextView:

adapter.notifyDataSetChanged();   
Flexo
  • 87,323
  • 22
  • 191
  • 272
Anshul Tyagi
  • 446
  • 3
  • 24