How to Use Autocompletetextview and Populate It with Data from a Web API

How do I Use AutoCompleteTextView and populate it with data from a web API?

I came up with a solution, I don't know if it is the best solution, but it appears to work very well. What I did was created a custom adapter that extends ArrayAdapter. In the custom adapter I overrode getFilter and created my own Filter class that overrides performFiltering. This starts a new thread so it doesn't interrupt the UI. Below is a barebones example.

MyActivity.java

public class MyActivity extends Activity {
private AutoCompleteTextView style;

@Override
public void onCreate(Bundle savedInstanceState) {
...
style = (AutoCompleteTextView) findViewById(R.id.style);
adapter = new AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line);
style.setAdapter(adapter);
}
}

AutoCompleteAdapter.java

public class AutoCompleteAdapter extends ArrayAdapter<Style> implements Filterable {
private ArrayList<Style> mData;

public AutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mData = new ArrayList<Style>();
}

@Override
public int getCount() {
return mData.size();
}

@Override
public Style getItem(int index) {
return mData.get(index);
}

@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint != null) {
// A class that queries a web API, parses the data and returns an ArrayList<Style>
StyleFetcher fetcher = new StyleFetcher();
try {
mData = fetcher.retrieveResults(constraint.toString());
}
catch(Exception e) {
Log.e("myException", e.getMessage());
}
// Now assign the values and count to the FilterResults object
filterResults.values = mData;
filterResults.count = mData.size();
}
return filterResults;
}

@Override
protected void publishResults(CharSequence contraint, FilterResults results) {
if(results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}

Populate AutoCompleteTextView from a remote API

you just want to do is set the data from(web api) into your AutoCompleteTextview's Adapter

A simple example :

in activity :

[Activity(Label = "AutoComplextActivity", MainLauncher = true)]
public class AutoComplextActivity : Activity
{
private ArrayAdapter<string> adapter;

protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);

// Create your application here
SetContentView(Resource.Layout.autocomplext_layout);
AutoCompleteTextView acTextView = (AutoCompleteTextView)FindViewById(Resource.Id.id_autotextView);
adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleDropDownItem1Line);
acTextView.Adapter=adapter;
GetData();
}

private void GetData()
{
//get data form web api,for example the data is below
List<string> data = new List<string>();
data.Add("beijing1");
data.Add("beijing2");
data.Add("beijing3");
data.Add("shanghai1");
data.Add("shanghai2");
data.Add("guangzhou1");
data.Add("shenzhen");
data.Add("adadadsgua");

//add data into adapter
adapter.AddAll(data);
adapter.NotifyDataSetChanged();
}
}

How to fill AutoCompleteTextView in Android with an API call?

kindly note that you are initializing your adatapter long before you make an api call, so I suggest that when your api returns data inside your public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) function, do reinitialise your adapter as below.

private void retrieveData(final AutoCompleteTextView s)
{
String text = s.toString();
if(text.contains(" "))
{
text.replace(" ", "%20");
}
String url = "https://api.edamam.com/api/food-database/parser?ingr="+text+"&app_id=8ff4be18&app_key=f2bf020e6d3cf1a9989c2a2163fb720f";
new AsyncHttpClient().get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
{
try
{
JSONObject foodNames=new JSONObject(new String(responseBody));
JSONArray jArray = foodNames.getJSONArray("hints");
for(int i = 0; i < jArray.length(); i++)
{
try
{
JSONObject hintItem = jArray.getJSONObject(i);
JSONObject foodItem = hintItem.getJSONObject("food");
String foodLabel = foodItem.getString("label");
apiFoods.add(foodLabel);
}
catch(JSONException e)
{

}
}

autoAdapter = new ArrayAdapter<>(ActivityName.this, android.R.layout.simple_dropdown_item_1line, apiFoods);

s.setAdapter(autoAdapter);

s.setThreshold(1);

s.setAdapter(adapter);

} catch (JSONException e)
{
e.printStackTrace();
}
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(), "API call failed", Toast.LENGTH_SHORT).show();
}
});
}

How to implement autocompletetextview in Android Studio with an API call?

Just create a simple adapter and update it every time you get results

  List<String> suggestions = new ArrayList<>();
ArrayAdapter<String> adapter ;
.
.
.
// in your onCreate

autocomplete = (AutoCompleteTextView)findViewById(R.id.stocks);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, suggestions);
autocomplete.setAdapter(arrayAdapter);

autocomplete.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) {
//retrieveData(s);
}

@Override
public void afterTextChanged(Editable s) {
retrieveData(s); //this will call your method every time the user stops typing, if you want to call it for each letter, call it in onTextChanged

}
});
.
.
.
// where you get the data, I suppose in a list
private void retrieveData(String s){
//Do your stuff here with the String s and store the list of your results in the list suggestions
suggestions = yourList;
adapter.notifyDataSetChanged();

}

Custom AutoCompleteTextview to fetch data from web Android

To provide auto-complete functionality do the following steps,

1.Implement a basic searchable activity, as described in Creating a Search Interface.
Modify the searchable configuration with information about the content provider that provides custom suggestions.

2.Build a table (such as in an SQLiteDatabase) for your suggestions and format the table with required columns.

3.Create a Content Provider that has access to your suggestions table and declare the provider in your manifest.

4.Declare the type of Intent to be sent when the user selects a suggestion (including a custom action and custom data).



Related Topics



Leave a reply



Submit