gpt4 book ai didi

java - 将数据传递到 RecyclerView 适配器

转载 作者:行者123 更新时间:2023-12-01 19:50:21 25 4
gpt4 key购买 nike

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

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

在我的主要 Activity 中:

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;
}
}

最佳答案

我的猜测是您使用 null mRecipeDataSet 启动 MyAdapter。尝试以下代码。

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){
return mRecipeDataSet;
}

public void setDataSet(List<Recipe> recipeList){
mRecipeDataSet = recipeList;
}

关于java - 将数据传递到 RecyclerView 适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51509347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com