Skip to content
Advertisement

How to fill AutoCompleteTextView in Android with an API call?

I want to try to get a list of food items from an API and update the AutoCompleteTextView based on this.

I’ve tried following the answer here but to no avail: https://stackoverflow.com/a/36799955/7429535

This is my code so far:

//Outside onCreate
List<String> apiFoods = new ArrayList<>();
//In onCreate
 AutoCompleteTextView autocomplete = (AutoCompleteTextView) findViewById(R.id.foodActv);
 final ArrayAdapter<String> autoAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, apiFoods);
 autocomplete.setAdapter(autoAdapter);

 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) {
         //retrieve data s
     }

     @Override
     public void afterTextChanged(Editable s) {
         retrieveData(s);
         autoAdapter.notifyDataSetChanged();
         Log.d("TAG", "foodsApi is " + apiFoods);
     }
});
//Below onCreate
private void retrieveData(Editable 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)
                    {

                    }
                }
            } 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();
        }
    });
}

You can see an example API response here: https://api.edamam.com/api/food-database/parser?ingr=red&app_id=8ff4be18&app_key=f2bf020e6d3cf1a9989c2a2163fb720f

Currently, this code IS inputting the correct food names into the apiFoods ArrayList but it is not showing me the options to select in app.

Advertisement

Answer

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();
        }
    });
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement