Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

AutoCompleteView: Synchronous Server Call With Filter

DZone 's Guide to

AutoCompleteView: Synchronous Server Call With Filter

In this post, we quickly go over how to use Java code to create a dynamically updating application using a few specific functions.

· Web Dev Zone ·
Free Resource

In order to implement a synchronous server calling within the filter, an autocomplete text view is being used. The web service is hit with each character typed in an Autocomplete list. To have data dynamically put into the list, we can make a customized adapter. I have implemented this by making an adapter to implement a filterable interface.

For getting data from the server, two approaches can be used:

1) Use the volley library:

@Override
public Filter getFilter() {
  Filter filter = new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
     final FilterResults filterResults = new FilterResults();
     if (constraint != null) {
      JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new com.android.volley.Response.Listener() {
       @Override
       public void onResponse(JSONObject response) {
        ResponseData responseData = new Gson().fromJson(response.toString(), ResponseData.class);
        if (responseData != null) {
         filterResults.values = responseData.getResponseData();
         filterResults.count = responseData.getResponseData().size();
        }
       }
      }, new com.android.volley.Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {}
      }) {
       @Override
       public Map getHeaders() throws AuthFailureError {
        return getCustomHeaders();
       }
      };
     }
     return filterResults;
    }

Volley requests can be made inside the performFiltering() function which gets a callback after each character is typed. But the problem in this approach is due to asynchronous requests, as a different thread is started and, before getting any result, the execution of the performFiltering() function stops. So we don't receive a result from server and, before that, the publishResults() function is called to display the result to UI.

2) Using Async Tasks:

@Override
public Filter getFilter() {
 Filter filter = new Filter() {
  @Override
  protected FilterResults performFiltering(CharSequence constraint) {
   final FilterResults filterResults = new FilterResults();
   if (constraint != null) {
    Object obj = WebServiceManager.callWebService();
    ResponseData responseData = new Gson().fromJson(obj.toString(), ResponseData.class);
    if (responseData != null) {
     filterResults.values = responseData.getResponseData();
     filterResults.count = responseData.getResponseData().size();
    }
   }
   return filterResults;
  }
  @Override
  protected void publishResults(CharSequence constraint, FilterResults results) {
   if (results != null && results.count > 0) {
    resultList = (List) results.values;
    notifyDataSetChanged();
   } else {
    notifyDataSetInvalidated();
   }
  }
 };
 return filter;
}

 

In WebServiceManager :

private static Object requestServer(String urlStr) {
 HttpURLConnection httpURLConnection = null;
 Object response = null;
 InputStream inputStream;
 int ch;
 try {
  URL url = new URL(urlStr);
  httpURLConnection = (HttpURLConnection) url.openConnection();
  httpURLConnection.setConnectTimeout(3000 * 10000); //Timeout until a connection is established
  httpURLConnection.setReadTimeout(3000 * 10000); //Timeout for waiting for data to come
  httpURLConnection.setRequestMethod("POST");
  httpURLConnection.setRequestProperty("Content-Type", "application/json");
  httpURLConnection.setDoInput(true);
  httpURLConnection.connect();
  inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
  StringBuffer stringBuffer = new StringBuffer();
  while ((ch = inputStream.read()) != -1) {
   stringBuffer.append((char) ch);
  }
  response = stringBuffer.toString();
 } catch (Exception exception) {
  exception.printStackTrace();
 } finally {
  httpURLConnection.disconnect();
 }
 return response;
}

Being a synchronous call, the call is made to the server and the results are obtained before the performFiltering() function stops executing. So the autocomplete list is obtained.

Topics:
web dev ,java ,tutorial ,synchronous server ,web application development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}