简体   繁体   English

单击按钮获取api后如何在片段中显示recyclerview

[英]how to display recyclerview in a fragment after fetching an api on the click of a button

I am trying to display some recipe data after you search the recipe in the search bar and click the search button inside the search fragment.在搜索栏中搜索食谱并单击搜索片段内的搜索按钮后,我正在尝试显示一些食谱数据。 I am using recycler view inside the search fragment to display the data below the search bar and the button.我在搜索片段中使用回收器视图来显示搜索栏和按钮下方的数据。

Here is the code for the fragment_search.xml file这是 fragment_search.xml 文件的代码

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.SearchFragment">

    <!-- TODO: Update blank fragment layout -->
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="100dp"
            android:layout_marginTop="-230dp"
            android:src="@drawable/home_oval" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="FOODIES"
                android:textSize="40dp"
                android:layout_centerHorizontal="true"/>

        </RelativeLayout>



        <SearchView
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="100dp"
            android:queryHint="Find your today's recipe"
            android:iconifiedByDefault="false"
            android:background="@drawable/searchoval"
            android:id="@+id/searchbar"
            />
        <Button
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="search"
            android:background="@drawable/rounded_btn"
            android:layout_below="@+id/searchbar"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:id="@+id/button1"/>

        <ImageView
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:layout_centerHorizontal="true"
            android:src="@drawable/ic_man_searching_location_using_gps_2127154_0"
            android:layout_below="@+id/button1"
            android:id="@+id/searching_logo"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/searching_text"
            android:text="Search for yummy delicacies today"
            android:layout_centerHorizontal="true"
            android:textAlignment="center"
            android:fontFamily="@font/quicksand"
            android:layout_below="@+id/searching_logo"
            android:textSize="25dp"
            android:textColor="@color/black"/>

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/button1"
            android:id="@+id/recycler_view"
            >


        </androidx.recyclerview.widget.RecyclerView>


    </RelativeLayout>



</FrameLayout>

Here is my SearchFragment.java file.这是我的 SearchFragment.java 文件。

package com.example.recipeappandroid.Fragments;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class SearchFragment extends Fragment {

    Button click;
    //public static TextView fetchedText;
    ImageView searching_logo;
    TextView searching_text;
    SearchView searchbar;
    String query="";
    RecyclerView recyclerView;
    public static ArrayList<Recipe> recipeList;
    public static RecipeAdapter recipeAdapter;
    private  RequestQueue mRequestQueue;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_search, container, false);

        click = (Button) view.findViewById(R.id.button1);
        //fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
        searchbar = (SearchView) view.findViewById(R.id.searchbar);
        searching_logo = view.findViewById(R.id.searching_logo);
        searching_text = view.findViewById(R.id.searching_text);
        recyclerView = view.findViewById(R.id.recycler_view);

        recyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(linearLayoutManager);
        //recipeAdapter = new RecipeAdapter();
        recyclerView.setAdapter(recipeAdapter);
        recipeList = new ArrayList<>();
        //getData();



        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query = searchbar.getQuery().toString();
                String url = "http://localhost:5000/" + query;
                JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        try {
                            for (int i = 0; i < response.length(); i++) {
                                JSONObject jsonObject = response.getJSONObject(i);
                                JSONObject recipes = jsonObject.getJSONObject("recipe");
                                //Recipe recipe = new Recipe();
                                String recipe_img = recipes.getString("image");
                                String recipe_title = recipes.getString("label");
                                String recipe_data =  recipes.getString("source");
                                recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
                            }
                            recipeAdapter = new RecipeAdapter(getContext(), recipeList);
                            //recyclerView.setAdapter(recipeAdapter);
                            recipeAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
                        error.printStackTrace();
                    }
                });
                mRequestQueue = Volley.newRequestQueue(getContext());
                mRequestQueue.add(jsonArrayRequest);
               /* Log.d("QUEEEERRRYYYY",query);
                ApiCall process = new ApiCall(searching_logo,searching_text);
                process.execute(query);*/


            }
        });

        return view;

    }

}

I am fething the api and setting the arraylists and adapter inside the onClick listener but I keep getting the "E/RecyclerView: No adapter attached; skipping layout" Error in the logcat.我正在使用 api 并在 onClick 侦听器中设置数组列表和适配器,但我不断收到“E/RecyclerView:未连接适配器;跳过布局”日志中的错误。

Here is the code for the adapter.这是适配器的代码。

 package com.example.recipeappandroid.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import com.example.recipeappandroid.Viewholder.recipeViewHolder;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;


public class RecipeAdapter extends RecyclerView.Adapter<recipeViewHolder>{
    private Context mContext;
    private ArrayList<Recipe> mRecipe;


    public RecipeAdapter(Context context,ArrayList<Recipe> recipe) {
        mContext = context;
        mRecipe = recipe;
    }

    public void setData(ArrayList<Recipe> mRecipe) {
        this.mRecipe = mRecipe;
    }

    @NonNull
    @Override
    public recipeViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_row, viewGroup, false);
        return new recipeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull recipeViewHolder viewHolder, int i) {
        Recipe recipe = mRecipe.get(i);
        Picasso.get().load(recipe.getImg()).into(viewHolder.image);
        viewHolder.recipe_title.setText(recipe.getTitle());
        viewHolder.recipe_data.setText(recipe.getData());
    }

    @Override
    public int getItemCount() {
        return mRecipe.size();
    }
}

Here is my solution这是我的解决方案

//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();

//change code:
recipeList = new ArrayList<>();
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
recyclerView.setAdapter(recipeAdapter);

//after get data in API:
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM