0

I have been trying to populate the autocompletetextview with JSON using an API but it's not working as the JSON API does not have an Array name. If I try to use some other API that does have an array name it's working fine.

This is the example link for the API.

I have tried implementing this answer but it's not working.

enter image description here

This is the structure of the API.

And this is my method.

private void populateEduList() {
    List<String> responseList = new ArrayList<>();
    String url = "https://autocomplete.clearbit.com/v1/companies/suggest?query=amazon";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, response -> {

        try {
            JSONArray jsonArray = new JSONArray(response);
            for (int i = 0; i < jsonArray.length(); i++){
                JSONObject object = jsonArray.getJSONObject(i);
                responseList.add(object.getString("name"));
                ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, responseList);
                mAutoCompEdu.setAdapter(adapter);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }, error -> {
        //do something for the error
    });

    requestQueue.add(request);
}

I have been using the Volley Library to fetch the JSON and parse it.

Aditya Verma
  • 120
  • 2
  • 10

1 Answers1

0

This is the answer, to fetch and display JSON in an autocompleteTextView if the JSON Array does not have a Name, we have to use StringRequest instead of JsonObjectRequest.

Updated Code.

private void populateEduList() {
        List<String> responseList = new ArrayList<>();
        String url = "https://autocomplete.clearbit.com/v1/companies/suggest?query=amazon";
        StringRequest request = new StringRequest(Request.Method.GET, url, response -> {
            try {
                JSONArray jsonArray = new JSONArray(response);
                for (int i = 0; i < jsonArray.length(); i++){
                    JSONObject object = jsonArray.getJSONObject(i);
                    responseList.add(object.getString("name"));
                    Log.d("hasjkd", object.getString("name"));
                    ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, responseList);
                    mAutoCompEdu.setAdapter(adapter);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }, error -> {
            //do something for the error
        });

        requestQueue.add(request);
    }
Aditya Verma
  • 120
  • 2
  • 10