[英]Passing Data to RecyclerView Adapter
I make a call to retrofit, and the size of the response is what I want to pass as the primary data set for my RecyclerView adapter. 我打电话给改造,响应的大小就是我希望作为RecyclerView适配器的主要数据集传递的大小。 I can confirm I am successfully calling to Retrofit.
我可以确认我已成功致电Retrofit。
I am curious how I would pass the size of the data set to MyAdapter class. 我很好奇如何将数据集的大小传递给MyAdapter类。 Below is my code:
下面是我的代码:
In my Main 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());
}
});
MyAdapter: MyAdapter:
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;
}
}
My guess is you initiate the MyAdapter
with null mRecipeDataSet
. 我的猜测是,你开始
MyAdapter
与空mRecipeDataSet
。 Try the following code. 请尝试以下代码。
private List<Recipe> mRecipeDataSet = new ArrayList<Recipe>();
and replace your code 并替换您的代码
//this is wrong, it doesn't do the right thing as the function name suggests.
public List<Recipe> setDataSet(List<Recipe> recipeList){
return mRecipeDataSet;
}
to 至
public void setDataSet(List<Recipe> recipeList){
mRecipeDataSet = recipeList;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.