DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

AutoCompleteView: Synchronous Server Call With Filter

Want to learn how to perform synchronous server calling within a filter? Check out this post to learn how using the AutoCompleteView method in Java.

Abhishek Tripathi user avatar by
Abhishek Tripathi
·
Oct. 05, 18 · Tutorial
Like (3)
Save
Tweet
Share
8.71K Views

Join the DZone community and get the full member experience.

Join For Free

In order to implement synchronous server calling within a filter, autocomplete textview is used. Web service is hit with each character typed in the Autocomplete list. For having data dynamically in the list, we can make a customized adapter. I have implemented it by making this adapter implement the filterable interface.

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

1) Using 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;
}


The volley request 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 request. 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 the server or before the publishResults() function is called to display the result to UI.

2) Using Async Task

@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 the synchronous call, a call is made to the server and the results are obtained before the performFiltering() function stops executing. Congrats! The autocomplete list is obtained.

Filter (software)

Published at DZone with permission of Abhishek Tripathi. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 5 Factors When Selecting a Database
  • Key Considerations When Implementing Virtual Kubernetes Clusters
  • Load Balancing Pattern
  • Distributed SQL: An Alternative to Database Sharding

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: