将数据传递给 RecyclerView 适配器

我调用了改造,响应的大小就是我想作为 RecyclerView 适配器的主要数据集传递的。我可以确认我已成功调用 Retrofit。


我很好奇如何将数据集的大小传递给 MyAdapter 类。下面是我的代码:


在我的主要活动中:


call.enqueue(new Callback<List<Recipe>>() {

        @Override

        public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) {

            Log.v("TAG", String.valueOf(response.isSuccessful()));

            mRecipeListResponse = response.body();

            for (Recipe recipe : mRecipeListResponse){

                Log.v("ID", recipe.getId().toString());

            }


            mAdapter.setDataSet(mRecipeListResponse);

            mRecipeList.setAdapter(mAdapter);

  ;            }


        @Override

        public void onFailure(Call<List<Recipe>> call, Throwable t) {

            Log.v("TAG", t.getMessage());

        }

    });

我的适配器:


public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {


private List<Recipe> mRecipeDataSet;


public class ViewHolder extends RecyclerView.ViewHolder{



    protected CardView mCardView;

    protected TextView mTextView;


    public ViewHolder(View itemView) {

        super(itemView);


        mCardView = itemView.findViewById(R.id.recipe_cardview);

        mTextView = itemView.findViewById(R.id.id_of_recipe_item);

    }

}

@NonNull

@Override

public MyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item, parent,false);

    return new ViewHolder(v);

}


@Override

public void onBindViewHolder(@NonNull MyAdapter.ViewHolder holder, int position) {

        String id = mRecipeDataSet.get(position).getId();

        holder.mTextView.setText(id);


}


@Override

public int getItemCount() {

    return mRecipeDataSet.size();

}


public List<Recipe> setDataSet(List<Recipe> recipeList){

    return mRecipeDataSet;

}


public List<Recipe> getmRecipeDataSet() {

    return mRecipeDataSet;

}

}


江户川乱折腾
浏览 169回答 1
1回答

RISEBY

我的猜测是你MyAdapter用 null启动mRecipeDataSet。试试下面的代码。private List<Recipe> mRecipeDataSet = new ArrayList<Recipe>();并替换您的代码//this is wrong, it doesn't do the right thing as the function name suggests.public List<Recipe> setDataSet(List<Recipe> recipeList){&nbsp; &nbsp; return mRecipeDataSet;}至public void setDataSet(List<Recipe> recipeList){&nbsp; &nbsp; mRecipeDataSet = recipeList;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java