ZOFTINO.COM android and web dev tutorials

Android AutoCompleteTextView Web Service Suggestions

Using Android AutoCompleteTextView widget, you can show suggestion dropdown for auto completion of entering input into text views. You can read android autocompletetextview tutorial to know how to use AutoCompleteTextView and its properties.

In this post, you can learn how to get data from remote service and populate auto complete dropdown with an example. This example uses Retrofit to call web service and get data for auto suggestion feature of AutoCompleteTextView.

This example requires internet permission, so add internet permission to android manifest file. Retrofit client runs asynchronously and adds array adapter to AutoCompleteTextView after receiving data from the remote service.

Project Dependency

Since Retrofit is used in this example, add below retrofit libraries dependencies to project.

 dependencies {
    . . .

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
}

Android AutoCompleteTextView Web Service Suggestions Example Output

android autocompletetextview remote webservice suggestion example

Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android.support.design="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.TextInputLayout
        android:id="@+id/store_til"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
        <AutoCompleteTextView
            android:id="@+id/store"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Store">
        </AutoCompleteTextView>
    </android.support.design.widget.TextInputLayout>
</android.support.constraint.ConstraintLayout>

Activity

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class AutoCompleteRemoteActivity extends AppCompatActivity {
    private AutoCompleteTextView storeTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remoteautodata);

        //gets remote data asynchronously and adds it to AutoCompleteTextView
        RemoteData remoteData = new RemoteData(this);
        remoteData.getStoreData();

       storeTV = (AutoCompleteTextView)findViewById(R.id.store);
       storeTV.setOnItemClickListener(onItemClickListener);
    }

    private AdapterView.OnItemClickListener onItemClickListener =
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    Toast.makeText(AutoCompleteRemoteActivity.this,
                            "Clicked item "
                                    + adapterView.getItemAtPosition(i)
                            , Toast.LENGTH_SHORT).show();
                }
            };
}

Remote Service Retrofit Client

package zoftino.com.uicontrols;


import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;

public class RemoteData {
    private Context context;

    public static final String BASE_URL = "http://www.zoftino.com/api/";
    private static Retrofit retrofit = null;

    public RemoteData(Context contextIn){
        context = contextIn;

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public interface StoreDataService {
        @GET("coupons/")
        Call<StoreDataWrapper> getStoreData();
    }

    public void getStoreData(){

         retrofit.create(StoreDataService.class).getStoreData()
                 .enqueue(new Callback<StoreDataWrapper>() {

             @Override
             public void onResponse(Call<StoreDataWrapper> call,
                                    Response<StoreDataWrapper> response) {

                 Log.d("Async Data RemoteData",
                         "Got REMOTE DATA "+response.body().getCoupons().size());

                 List<String> str = new ArrayList<String>();
                 for(StoreData s : response.body().getCoupons()){
                     str.add(s.getStore());
                 }

                 AutoCompleteTextView storeTV =
                         (AutoCompleteTextView)((Activity)context).findViewById(R.id.store);

                 ArrayAdapter<String> adapteo = new ArrayAdapter<String>(context,
                         android.R.layout.simple_dropdown_item_1line, str.toArray(new String[0]));
                 storeTV.setAdapter(adapteo);
             }
             @Override
             public void onFailure(Call<StoreDataWrapper> call, Throwable t) {
                 Log.e("Async Data RemoteData",
                         "error in getting remote data");
             }
         });
    }
}

Data Model

public class StoreData {

    private String store;

    public String getStore() {
        return store;
    }

    public void setStore(String store) {
        this.store = store;
    }
}
public class StoreDataWrapper {
    private List<StoreData> coupons;

    public List<StoreData> getCoupons() {
        return coupons;
    }

    public void setCoupons(List<StoreData> coupons) {
        this.coupons = coupons;
    }
}