You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中hospitalListAdapter实例化报错及RecyclerView问题求助

解决RecyclerView适配器实例化参数不匹配问题

问题原因

你的hospitalListAdapter构造函数要求传入Context和**ArrayList**两个参数,但在hospitalActivity中实例化时仅传入了Context,导致参数不匹配,触发报错。


解决方案(二选一即可)

方案一:给适配器添加单参数构造函数

修改hospitalListAdapter.java,新增一个仅接收Context的构造方法,同时保留原有的双参数构造函数以兼容其他场景:

public class hospitalListAdapter extends RecyclerView.Adapter<hospitalListAdapter.ViewHolder> {
    Context mContext;
    ArrayList<hospitalListItem> items = new ArrayList<>();

    // 新增单参数构造函数
    public hospitalListAdapter(Context mContext) {
        this.mContext = mContext;
        this.items = new ArrayList<>();
    }

    // 保留原双参数构造函数
    public hospitalListAdapter(Context mContext, ArrayList<hospitalListItem> items) {
        this.mContext = mContext;
        this.items = items;
    }

    // 其余代码不变...
}

修改后,原adapter = new hospitalListAdapter(getApplicationContext());代码可正常运行,后续调用addItem添加数据不受影响。

方案二:在Activity中先初始化列表再传入适配器

修改hospitalActivity.java的onCreate方法,先创建空列表,再将Context和列表一起传入适配器:

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

    hospital_list = findViewById(R.id.hospital_list);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    hospital_list.setLayoutManager(layoutManager);

    // 先初始化空列表
    ArrayList<hospitalListItem> hospitalList = new ArrayList<>();
    // 传入Context和列表实例化适配器
    adapter = new hospitalListAdapter(this, hospitalList);
    hospital_list.setAdapter(adapter);

    // 后续添加数据代码保持不变
    adapter.addItem(new hospitalListItem(R.drawable.nuribom, "동물병원", "종로구","02-33", "어쩌구저쩌구"));
    // ... 其他addItem代码
}

小提示

实例化适配器时,建议用this(Activity本身作为Context)代替getApplicationContext(),可避免潜在的内存泄漏风险。

内容的提问来源于stack exchange,提问作者kimzero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:43:15