gpt4 book ai didi

java - RecyclerAdapter getItemCount 崩溃

转载 作者:行者123 更新时间:2023-12-02 10:39:40 25 4
gpt4 key购买 nike

我遇到以下问题,不幸的是,我的应用程序在进入下一个 Activity 时停止了。罪魁祸首是:

   public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerHolder> {

ArrayList<Theme> themes;
private LayoutInflater mInflater;

public RecyclerAdapter(Context context, ArrayList<Theme> themes) {
mInflater = LayoutInflater.from(context);
this.themes = themes;
}

public class RecyclerHolder extends RecyclerView.ViewHolder {

ImageView imageView;
TextView name,price;

public RecyclerHolder(View view) {
super(view);
imageView = (ImageView)view.findViewById(R.id.demo);
name = (TextView)view.findViewById(R.id.name);
price = (TextView)view.findViewById(R.id.price);
}
}

@NonNull
@Override
public RecyclerHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = mInflater.inflate(R.layout.recycler_list, viewGroup, false);
return new RecyclerHolder(view);
}

@Override
public void onBindViewHolder(@NonNull RecyclerHolder viewHolder, int i) {
Log.i("log", themes.get(i).getName());
viewHolder.imageView.setImageResource(themes.get(i).getDrawableCover());
viewHolder.name.setText(themes.get(i).getName());
viewHolder.price.setText(themes.get(i).getPrice());
}

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

问题似乎出在 getItemCount() 方法上。当我尝试返回themes.size()时,应用程序崩溃了。当我 return 0 时,什么也没有显示。这里似乎有什么问题?我是android新手,所以请正确解释。

最佳答案

您想在 getItemCount() 方法中检查数据是否为 ​​null,这样您就可以确保您的应用永远不会崩溃:

Java:

@Override
public int getItemCount() {
return themes != null ? themes.size() : 0;
}

Kotlin :

override fun getItemCount(): Int = themes?.size ?: 0

关于java - RecyclerAdapter getItemCount 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53018699/

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