2

I have somehow implemented incremental search in android using AsyncTask. In incremental search an API is called for each character entered in edit text to get suggestions from server. For example,

User types a -> API is called.
User types ab -> API is called.
User types abc -> API is called. 

This makes three API calls for a, ab and abc respectively. If a user is still typing then all the previous requests (e.g. requests of a and ab) will be cancelled and the last request (abc) will be served only to avoid delays.

Now I want to implement this using Volley library for better performance. Could anybody help me how can I achieve this functionality using volley specially the mechanism of cancelling all the previous request and serve the last request only to get suggestions from server.

NOTE: I couldn't find regarding this that's why posting it here. Please do guide me because I am new to android and really in need of answer.

1 Answers1

1

First you need to implement a TextWatcher to listen to change in edit text. Depending on the requirement of the changed text, you cancel and add a request to queue.

private RequestQueue queue = VolleyUtils.getRequestQueue();


private static final String VOLLEY_TAG = "VT";
private EditText editText;
...

 TextWatcher textChangedListener = new TextWatcher() {

          @Override
          public void afterTextChanged(Editable s) {}

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

          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (s.length() != 0) {
                // first cancel the current request with that tag
                queue.cancelAll(VOLLEY_TAG);
                // and then add a new one to queue
                StringRequest stringRequest = 
                     new StringRequest("http://blabla/servlet?param=" + s, 
                     new Listener<String>() {
                       // request callbacks
                     };
                stringRequest.setTag(VOLLEY_TAG);
                queue.add(stringRequest);
            } 
        }
  };

editText.addTextChangedListener(textChangedListener);

Just remember that this design will gobble up bandwidth. A better way is to use Handler.post() to wait for several seconds before firing a request.

inmyth
  • 8,880
  • 4
  • 47
  • 52