0

I am currently using the Yummly API which returns recipe data in the form of JSON. The user enters an ingredient and the app should display recipes which can be made from that ingredient. So far the search works and I have successfully retrieved a list of recipe names, of which I have added to an ArrayList.

I am able to print all the contents of the ArrayList to the terminal in the onPostExecute() method, so there is definitely data inside the ArrayList. However for some reason it's not displaying inside the ListView! I am able to reach the results page, but all I get is a blank page.

Search.java

public class Search extends Fragment {

EditText ingredient;
Activity mActivity;
ArrayList<String> pairs = new ArrayList<>();
private static final String TAG_TOTAL_MATCH = "totalMatchCount";
private static final String TAG_MATCHES = "matches";
private static final String TAG_NAME = "recipeName";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.searchpage, container, false);

    Button btnSearch = (Button) rootView.findViewById(R.id.search_button);

    btnSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ingredient = (EditText) getView().findViewById(R.id.search_box);
            // search returns something
            new SearchRecipe().execute();
        }
    });

    return rootView;
}

    class SearchRecipe extends AsyncTask<String, String, ArrayList<String>> {

    private String search_string;
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();

    /**
     * Searching for recipes
     * */
    protected ArrayList<String> doInBackground(String... args) {


        String full_url = url_search_recipe + search_string;

        JSONObject json = jsonParser.makeHttpRequest(full_url, "GET", params);

        // check log cat for JSON response
        Log.d("Response", json.toString());

        // check for success tag
        try {
            int count = json.getInt(TAG_TOTAL_MATCH);
            JSONArray matches = json.getJSONArray(TAG_MATCHES);

            if (count > 0) {
                int i;

                //populate array with recipe
                for (i=0; i<matches.length(); i++){
                    JSONObject js = matches.getJSONObject(i);
                    String name = js.getString(TAG_NAME);
                    pairs.add(name);

                }
                // return json.getString(TAG_MESSAGE);

            } else {
                // no results found
                // Toast.makeText(mActivity.getApplicationContext(), "There were: " + count + " recipes found", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(ArrayList<String> menu) {
        // dismiss the dialog once done
        pDialog.dismiss();
        //print recipes to terminal
        for(int j =0; j<pairs.size(); j++) {
            System.out.println(pairs.get(j));
        }
        FragmentManager fm = getActivity().getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.container, new Results());
        ft.commit();
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_resultspage, null);
        ListView myListView = (ListView) v.findViewById(R.id.resultsView);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, pairs);
        myListView.setAdapter(arrayAdapter);

    }

}
}

Results.java

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_resultspage, container, false);
        return rootView;
    }

fragment_resultspage.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#9ad979"
        android:id="@+id/resultsView"
        android:scrollbars="vertical"
        android:choiceMode="singleChoice" />

</RelativeLayout>

I think there's something obvious that I'm missing out but I'm at a loss. What could be the reason that it's not displaying anything? Only a fragment of my Search.java file is included, since it's over 200 lines long so I only included the relevant parts!

7
  • You are showing the result in a fragment. You have to pass the data obtained to that fragment and populate the list from there Commented Feb 16, 2016 at 4:55
  • when you add a fragment like you do, it is not displayed instantly. Then, when you inflate your view in onPostExecute, you don't add it to the hierarchy, so it is never displayed. A more common pattern is to add the content you want to displayed in your ResultFragment, typically in a factory method using the fragment arguments, then put the content in the view in the onCreateView Commented Feb 16, 2016 at 4:55
  • 1
    Use android:layout_height="match_parent" instead of android:layout_height="wrap_content" for ListView height :) Commented Feb 16, 2016 at 4:56
  • return pairs; in place of return null in doInBackground() Commented Feb 16, 2016 at 4:58
  • The correct usage of onPostExecute is to use its parameter, which is the return value from doInBackground Commented Feb 16, 2016 at 4:59

1 Answer 1

3

Do this in your result fragment. You need to pass the data obtained from the service to your Result fragment first.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View rootView = inflater.inflate(R.layout.fragment_resultspage, container, false);
    ListView myListView = (ListView) rootView.findViewById(R.id.resultsView);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), 
                                     android.R.layout.simple_list_item_1, 
                                                               YOUR_RESULT);
    myListView.setAdapter(arrayAdapter);
    return rootView;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worked! Thank you sir!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.