0

I have created an AsyncTask to fetch suggestions from a URL every time there is a change on an AutoCompleteTextView. It should work fine, I don't know what the problem is.

Fragment (with AutoCompleteTextView):

atv = (AutoCompleteTextView) view.findViewById(R.id.atvMovieName);
// adding event listeners for text on the auto complete text view
atv.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
         SuggestionFetcher fetcher = new SuggestionFetcher(getActivity(), atv);
         String title = s.toString().replace(" ", "%20");
         try {
             URL url = new URL("http://imdbapi.com/?s=" + title + "&r=xml");
             fetcher.execute(url);
         } catch (MalformedURLException e) {
             e.printStackTrace();
         }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

SuggestionFetcher:

// suggestion titles will be saved here
private Stack<String> suggestions;

// this is the auto complete text view we will be handling
private AutoCompleteTextView atv;
// and it's adapter
private ArrayAdapter<String> adapter;
// context of the activity or fragment
private Context context;

private static final String TAG = "Suggestion Fetcher";

public SuggestionFetcher(Context c, AutoCompleteTextView atv) {
    this.atv = atv;
    this.context = c;
    this.suggestions = new Stack<String>();
}

@Override
protected Stack<String> doInBackground(URL... params) {
    // get the data...
    this.suggestions.add(title);

    return this.suggestions;
}

@Override
protected void onPostExecute(Stack<String> strings) {
    super.onPostExecute(strings);
    Log.v(TAG, "finished with the data: " + strings); // works, shows the results I wanted
    // update the list view
    this.adapter = new ArrayAdapter<String>(this.context, android.R.layout.simple_list_item_1, strings);
    this.atv.setAdapter(this.adapter);
}

As I wrote in the comments, it actually gets the data, but I get no suggestions.

Gofilord
  • 6,239
  • 4
  • 27
  • 43

1 Answers1

1

I had the same task to implement and for that I used a hidden listview below the edittext(where i enter the url or search term) and the listview will be populated from the api on the basis of change in editext using textwatcher.Try this if you need another solution.

Karthika PB
  • 1,373
  • 9
  • 16