CAM3R0N
CAM3R0N

Reputation: 1

Android Studio Get data from a user input searched API

I am using Android Studio and I am trying to make it so that whatever the user types into the searchview, it will be passed into the API call as a parameter and then return all the data based on each search into a recycler view. I have tried this both with volley and Gson.

In my activity I have a query listener and I have what I was shown to be used to get JSON data and put it into a string in the onQueryTextChange. With each letter typed in I want it to make the call to the API and return the data it gets to my setData, function to be put into the recycler view.

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {

         String url = "https://fdc.nal.usda.gov/fdc/v1/foods/search?=" + newText + "&dataType=Foundation,SR%20Legacy&api_key=my_apikey";

                        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray(" foods");
                            for (int i = 0; i < jsonArray.length(); i++)
                            {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String foodname = jsonObject.getString("description");
                                String proteingrams = jsonObject.getString("value");

                                setData(foodname, proteingrams);
                            }

                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(SearchFoods.this, error.getMessage(), Toast.LENGTH_SHORT);
                    }
                });

                requestQueue.add(jsonObjectRequest);
        
        return true;

    }
});

This is for my recyclerview list, which I have a model set up to be able to add to this list. Right now I am using 2 String values for right now to just try and get it to work

public void setData(String foodname, String proteingrams)
    {
        foodModelList.add(new FoodModel(foodname.toString(), "70", "14", proteingrmas.toString(), "47.6", "11.9", "2.7", "1"));
    }

Upvotes: 0

Views: 49

Answers (0)

Related Questions