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

如何为TextView设置ArrayList中Recipe的category_name?报错求助

Android中为TextView设置List元素属性的错误修复方案

你出错的核心原因是直接访问List集合对象的category_name属性,但List<Recipe>是一个集合容器,本身并没有这个属性,category_name是集合中单个Recipe对象的属性。此外,直接操作集合元素前未做非空判断,还会引发空指针异常。

修正步骤:

  1. 先判断集合是否为空,避免空指针
  2. 获取集合中的具体Recipe元素(比如第一个元素),再访问其category_name属性

修正后的代码片段:

private void displaypost1(List<Recipe> list) {
    // 先判断集合非空,再获取元素设置文本
    TextView titleTv = root_view.findViewById(R.id.txt_title_post1);
    if (list != null && !list.isEmpty()) {
        Recipe firstRecipe = list.get(0);
        titleTv.setText(firstRecipe.category_name);
    } else {
        // 集合为空时设置默认文本或隐藏TextView
        titleTv.setText("暂无分类");
        // 或者隐藏:titleTv.setVisibility(View.GONE);
    }

    // 以下RecyclerView相关代码保持不变
    RecyclerView recyclerView = root_view.findViewById(R.id.recycler_view_post1);
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
    Adapterpost1 adapterpost1 = new Adapterpost1(getActivity(), recyclerView, list);
    recyclerView.setAdapter(adapterpost1);
    recyclerView.setNestedScrollingEnabled(false);
    adapterpost1.setOnItemClickListener((view, obj, position) -> {
        Intent intent = new Intent(getActivity(), ActivityRecipeDetail.class);
        intent.putExtra(Constant.EXTRA_OBJC, obj);

        startActivity(intent);
        ((MainActivity) Objects.requireNonNull(getActivity())).showInterstitialAd();
    });

    LinearLayout lyt_recipes = root_view.findViewById(R.id.lyt_recipes);
    if (list != null && list.size() > 0) {
        lyt_recipes.setVisibility(View.VISIBLE);
    } else {
        lyt_recipes.setVisibility(View.GONE);
    }
}

额外说明:

  • 如果你的需求是显示所有元素的category_name(比如拼接成字符串),可以这样处理:
if (list != null && !list.isEmpty()) {
    StringBuilder categoryNames = new StringBuilder();
    for (Recipe recipe : list) {
        categoryNames.append(recipe.category_name).append(" ");
    }
    titleTv.setText(categoryNames.toString().trim());
}
  • 确保你的Recipe实体类中正确定义了category_name字段,并且JSON解析时已经正确赋值(比如用Gson/Jackson等解析库时,字段名要和JSON中的category_name匹配,或者用注解映射)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:10:30