尝试在recyclerview中的空对象引用上调用接口方法'int java.util.List.size()'

时间:2019-06-07 13:08:44

标签: java android nullpointerexception

大家好,我正在使用某个应用程序,并且正在使用Retrofit2来使用rest api。我有需要使用recyclerview显示的公司列表。我已经阅读了很多资源和教程,但是都没有帮助。在logcat会话中,我遇到一个错误:java.lang.NullPointerException:尝试在我的适配器中的空对象引用上调用接口方法'int java.util.List.size()'。...

在此行:

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

这是我的代码: 我的适配器

private List<Company> companies;
private Context context;

public CompanyAdapter(List<Company> companies, Context context) {
    this.companies = companies;
    this.context = context;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.row_companies, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
    Company comp = companies.get(position);

    viewHolder.compName.setText(comp.getName());
    viewHolder.compDesc.setText(comp.getDescription());
    viewHolder.compNipt.setText(comp.getNipt());
}

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

public class ViewHolder extends RecyclerView.ViewHolder {

    public TextView compName, compDesc, compNipt;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        compName = (TextView) itemView.findViewById(R.id.tvCompanyName);
        compDesc = (TextView) itemView.findViewById(R.id.tvCompanyDescription);
        compNipt = (TextView) itemView.findViewById(R.id.tvCompanyNipt);
    }
}

和我的活动

private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Company> companies;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_companies_list);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.companies_list);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    adapter = new CompanyAdapter(companies, this);
    recyclerView.setAdapter(adapter);
}

我做错了什么... 任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

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