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. I can confirm I am successfully calling to Retrofit.
I am curious how I would pass the size of the data set to MyAdapter class. 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:
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
. 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.