Android:无法转换为 java.lang.CharSequence

2024-03-11

我不知道我哪里出了问题,我试图在 recyclerView 中列出食谱的成分,但我无法让 onBindViewHolder 正常工作,无论我尝试过什么。下面是适配器代码以及 xml Recipe.class。本质上我需要将 Recipe 类的结果显示到 recyclerView。

菜谱类

public class Recipe extends MainActivity {

    TabLayout tabLayout;
    ImageView recipeImage;
    TextView descriptionText, courseText, servingsText, costText, caloriesText, methodText;
    RecyclerView listIngredient;
    SQLiteDatabase db;
    String search_name;
    Cursor c;
    RecyclerViewAdapter adapterRecipe;
    List<RecipeList> itemRecipe = new ArrayList<>();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recipe);
        //search_name = getIntent().getStringExtra("NAME");
        search_name = "Speedy chicken couscous";

        loadRecipe();
        //recyclerview Recipe
        adapterRecipe = new RecyclerViewAdapter(this, itemRecipe);
        listIngredient = findViewById(R.id.listIngredient);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        listIngredient.setLayoutManager(mLayoutManager);
        listIngredient.setItemAnimator(new DefaultItemAnimator());
        listIngredient.setAdapter(adapterRecipe);

    }
    public void loadRecipe() {
        itemRecipe.clear();
        db = (new DatabaseManager(this).getWritableDatabase());
        String RECIPE_SEARCH = " SELECT A.recipe, A.ingredient_quantity, B.measurement_name, B.ingredient_name, B.description " +
                "FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS +
                " AS B ON A.ingredient = B.ingredient_name";
        String selectQuery = "";
        selectQuery = RECIPE_SEARCH + " WHERE A.recipe LIKE ?";
        c = db.rawQuery(selectQuery, new String[]{"%" + search_name + "%"});
        if (c.moveToFirst()) {
            do {
                RecipeList recipeList = new RecipeList();
                recipeList.setRecipe(c.getString(c.getColumnIndex("recipe")));
                recipeList.setIngredient_amount(c.getString(c.getColumnIndex("ingredient_quantity")));
                recipeList.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
                recipeList.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
                recipeList.setDescription(c.getString(c.getColumnIndex("description")));
                itemRecipe.add(recipeList);
            } while (c.moveToNext());
            c.close();
        }

    }
}

XML

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/listIngredient"
    android:name="com.stu54259.plan2cook.Recipe"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginTop="8dp"
    app:layoutManager="LinearLayoutManager"
    app:layout_constraintBottom_toTopOf="@+id/guideline7"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/caloriesText"
    tools:context=".Recipe"
    tools:listitem="@layout/fragment_item">

</androidx.recyclerview.widget.RecyclerView>  

Adapter

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<RecipeList> itemRecipe;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;

// data is passed into the constructor
RecyclerViewAdapter(Context context, List<RecipeList> data) {
    this.mInflater = LayoutInflater.from(context);
    this.itemRecipe = data;
}

// inflates the row layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = mInflater.inflate(R.layout.fragment_item, parent, false);
    return new ViewHolder(view);
}

// binds the data to the TextView in each row
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.myTextView.setText(itemRecipe.get(position));

}

// total number of rows
@Override
public int getItemCount() {
    return itemRecipe.size();
}


// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView myTextView;

    ViewHolder(View itemView) {
        super(itemView);
        myTextView = itemView.findViewById(R.id.listIngredient);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
    }
}


// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
    this.mClickListener = itemClickListener;
}

// parent activity will implement this method to respond to click events
public interface ItemClickListener {
    void onItemClick(View view, int position);
}

完整日志

2020-09-17 13:21:35.570 15862-15862/? E/54259.plan2coo: Unknown bits set in runtime_flags: 0x8000
2020-09-17 13:21:50.653 15862-15862/com.stu54259.plan2cook E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.stu54259.plan2cook, PID: 15862
    java.lang.ClassCastException: com.stu54259.plan2cook.Model.RecipeList cannot be cast to java.lang.CharSequence
        at com.stu54259.plan2cook.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:37)
        at com.stu54259.plan2cook.RecyclerViewAdapter.onBindViewHolder(RecyclerViewAdapter.java:15)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:21912)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1762)
        at android.view.View.layout(View.java:21912)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
        at android.view.View.layout(View.java:21912)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
        at android.view.View.layout(View.java:21912)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
        at android.view.View.layout(View.java:21912)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1829)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1673)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1582)
        at android.view.View.layout(View.java:21912)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:332)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:270)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:779)
        at android.view.View.layout(View.java:21912)
        at android.view.ViewGroup.layout(ViewGroup.java:6260)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:3080)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2590)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1721)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7598)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:966)
        at android.view.Choreographer.doCallbacks(Choreographer.java:790)
        at android.view.Choreographer.doFrame(Choreographer.java:725)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:951)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
2020-09-17 13:21:50.653 15862-15862/com.stu54259.plan2cook E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

食谱列表模型公共类食谱列表{

    private Integer id;
    private Double ingredient_quantity;
    private String recipe;
    private String measurement_name;
    private String ingredient_name;
    private String description;
    private String ingredient_amount = String.valueOf(ingredient_quantity);
    public RecipeList(){

    }

    public RecipeList(String recipe, String ingredient_amount, String measurement_name, String ingredient_name, String description) {

        this.recipe = recipe;
        this.ingredient_amount = ingredient_amount;
        this.measurement_name = measurement_name;
        this.ingredient_name = ingredient_name;
        this.description = description;
    }

    public String getRecipe() {
        return recipe;
    }

    public void setRecipe(String recipe) {
        this.recipe = recipe;
    }

    public String getIngredient_amount() {
        return ingredient_amount;
    }

    public void setIngredient_amount(String ingredient_amount) {
        this.ingredient_amount = ingredient_amount;
    }

    public String getMeasurement_name() {
        return measurement_name;
    }

    public void setMeasurement_name(String measurement_name) {
        this.measurement_name = measurement_name;
    }

    public String getIngredient_name() {
        return ingredient_name;
    }

    public void setIngredient_name(String ingredient_name) {
        this.ingredient_name = ingredient_name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

更新错误

尝试在空对象引用上调用虚拟方法“void android.widget.TextView.setText(java.lang.CharSequence)”

在这一行: holder.myTextView.setText(itemRecipe.get(position).toString());


在代码中itemRecipe.get(position)正在返回RecipeList 您将这个对象直接传递给 setText,其中 setText 需要字符串,尝试在此处传递字符串值holder.myTextView.setText(//pass string)

将 RecipeList 作为字符串传递 覆盖 RecipeList 中的字符串

ex:这里添加了示例格式并包含了 toString 中的所有变量。

@Override
public String toString() {
    return "RecipeList{" +
            "id=" + id +
            ", ingredient_quantity=" + ingredient_quantity +
            ", recipe='" + recipe + '\'' +
            ", measurement_name='" + measurement_name + '\'' +
            ", ingredient_name='" + ingredient_name + '\'' +
            ", description='" + description + '\'' +
            ", ingredient_amount='" + ingredient_amount + '\'' +
            '}';
}

在 setText 中对 RecipeList 对象调用 toString

ex:

holder.myTextView.setText(itemRecipe.get(position).toString)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android:无法转换为 java.lang.CharSequence 的相关文章

  • 从响应中获取标头(Retrofit / OkHttp 客户端)

    我正在使用 Retrofit 与 OkHttp 客户端和 Jackson 进行 Json 序列化 并希望获取响应的标头 我知道我可以扩展 OkClient 并拦截它 但这发生在反序列化过程开始之前 我基本上需要的是获取标头以及反序列化的 J
  • AdapterContextMenuInfo 始终为 null

    我尝试通过 android 开发文档中的书来做到这一点 this didn t create a menu i don t know why registerForContextMenu getListView setListAdapter
  • 按下按钮时应用不同的样式

    有没有办法在按下按钮时将样式应用于按钮 如果我有一种风格样式 xml
  • 将现有 VARCHAR 列与 Room 结合使用

    我正在尝试将现有的数据库与 Android Room 一起使用 但是 我的一个表有一个 VARCHAR 列 Room 似乎只支持 TEXT 不支持 VARCHAR 而且 sqlite 不允许修改列类型 那么 有没有办法使用Room中现有的带
  • Android WebView里面的ScrollView只滚动scrollview

    在我的应用程序中 我有一个 ScrollView 其中包含一些线性视图 一些文本视图和一个 Webview 然后是其他线性布局等 问题是 WebView 不滚动 Scroll 仅侦听 ScrollView 有什么建议么
  • OnUpgrade SQFLITE:未处理的异常:DatabaseException(表 UsernameTable 没有名为 RememberMe 的列(Sqlite 代码 1):

    未处理的异常 DatabaseException 表 UsernameTable 没有 名为 RememberMe 的列 Sqlite 代码 1 编译时 INSERT OR 替换为 UsernameTable 用户名 rememberMe
  • Dialog.setTitle 不显示标题

    我正在尝试向我的对话框添加自定义标题 但是每当我运行我的应用程序时 它都不会显示标题 我创建对话框的代码是 final Dialog passwordDialog new Dialog this passwordDialog setCont
  • ExoPlayer2 - 如何使 HTTP 301 重定向工作?

    我开始使用 ExoPlayer 来传输一些音频 一切都很顺利 直到我遇到一个带有 301 永久移动 重定向的 URL ExoPlayer2 默认情况下不处理该问题 我已经看过这个线程 https github com google ExoP
  • 当 OnFocusChangeListener 应用于包装的 EditText 时,TextInputLayout 没有动画

    不能比标题说得更清楚了 我有一个由文本输入布局包裹的 EditText 我试图在 EditText 失去焦点时触发一个事件 但是 一旦应用了事件侦听器 TextInputLayout 就不再对文本进行动画处理 它只是位于 editText
  • 如何在谷歌地图android上显示多个标记

    我想在谷歌地图android上显示带有多个标记的位置 问题是当我运行我的应用程序时 它只显示一个位置 标记 这是我的代码 public class koordinatTask extends AsyncTask
  • okhttp 获取失败响应

    我已经在我的 android 客户端中实现了 okhttp 来进行网络调用 当我收到失败响应时 我会收到失败代码以及与该代码相关的文本作为消息 但我没有收到服务器发送给我的自定义失败响应 在我实施的代码中的失败响应中 我收到的消息只是 错误
  • Mipmap 与可绘制文件夹[重复]

    这个问题在这里已经有答案了 我正在使用 Android Studio 1 1 Preview 1 我注意到 当我创建一个新项目时 我得到以下层次结构 不同 DPI 的 Mipmap 文件夹 不再有不同 DPI 的可绘制文件夹 我应该将所有资
  • Android 中如何通过彩信发送图片?

    我正在开发多媒体应用程序 我正在通过相机捕获一张图像 并希望将该图像和文本发送到其他号码 但我不知道如何通过彩信发送图像 MMS 只是一个 http post 请求 您应该使用执行请求额外的网络功能 final ConnectivityMa
  • Android 2.3 模拟器在更新位置时崩溃

    我正在使用 Eclipse 编写和调试 Android 应用程序 我需要做的事情之一是更新设备的位置 因此我尝试使用模拟器控制窗口中的位置控制面板 在 手动 选项卡上 我选择 十进制 输入有效的纬度和经度 然后单击 发送 不幸的是 接下来发
  • 我应该释放或重置 MediaPlayer 吗?

    我有自己的自定义适配器类 称为 WordAdapter 并且我正在使用媒体播放器 名为pronounce WordAdapter 类中的全局变量 我有不同的活动 其中每个列表项都有线性布局 名为linearLayout 我正在设置onCli
  • OnLongClickListener 不工作

    我有一个ImageView 我需要使用onLongClickListener对于图像视图 当我使用这段代码时 什么也没有发生 Code gallery Gallery findViewById R id gall1 gallery setA
  • Android - 以编程方式选择菜单选项

    有没有办法以编程方式选择菜单选项 基本上 我希望视图中的按钮能够执行与按特定菜单选项相同的操作 我正在考虑尝试调用 onOptionsItemSelected MenuItem item 但我不知道要为菜单项添加什么 是的 有一种方法可以选
  • 错误:(23, 13) 无法解决:com.google.android.gms:play-services:11.2.0“安装存储库和同步项目”不起作用

    我正在尝试在我的 Android 应用程序中获取位置并更新到服务器 这是我的 Gradle 代码 我在这里包含了compile com google android gms play services 11 2 0 这条线是从文档中 htt
  • Android 后台倒计时器

    我有一个 Android 应用程序 它管理一个倒计时器 类 CountDownTimer 它显示在应用程序屏幕中 以显示到达 00 00 还剩多少时间 我现在的问题是 当我按主页按钮或启动另一个应用程序时 应用程序 计时器不会在后台运行 所
  • Android 屏幕方向错误

    我使用的是 Android HTC HERO 2 1 版本 我写的活动

随机推荐

  • 在 Qt Creator 中使用 Qt 标准图标

    我想使用 Qt Standard 图标 as here http standards freedesktop org icon naming spec icon naming spec latest html 我发现了很多例子如何以编程方式
  • Thymeleaf 不解释 sec 标签

    我遇到了一个问题 thymleaf 无法识别我的 Spring Boot 项目中的 sec 标签 例如下面的 sec authentication 未被解释 并按浏览器中的 html 中的形式显示 div Roles span span d
  • 从 Elasticsearch 文档中删除字段

    我需要删除索引到 Elasticsearch 的所有文档中的一个字段 我该怎么做 backtrack 所说的是 true 但是在 Elasticsearch 中有一种非常方便的方法可以做到这一点 Elasticsearch 会抽象出删除的内
  • SQLite .NET,ExecuteScalarAsync,如何知道何时没有结果?

    SQL 语句正在检索行的 ID 但可能不存在这样的行 当我在 GUI 工具中执行特定 SQL 语句时 它返回 0 行在 0 毫秒内返回 但是 当我执行相同的 SQL 语句时ExecuteScalarAsync
  • Spark Scala UDP 在侦听端口上接收

    中提到的例子http spark apache org docs latest streaming programming guide html http spark apache org docs latest streaming pro
  • curl 重新使用 https 连接会话

    我已经使用 openssl 构建了curl 并且能够执行https 连接 现在 每次当curl建立TLS连接时 它都会再次握手 我需要利用客户端与服务器的先前连接会话ID 并在下一个请求中使用它 我已经尝试过以下选项 但每次尝试仍然会进行新
  • 当您有列名的字符向量时,如何不使用 select() dplyr 选择列?

    我正在尝试使用 dplyr 取消选择数据集中的列 但自昨晚以来我无法实现这一目标 我很清楚解决方法 但我正在严格尝试通过 dplyr 找到答案 library dplyr df lt tibble x c 1 2 3 4 y c a b c
  • Angular 2 HTTP 响应拦截器

    在 Angular 1 中 全局处理 HTTP 响应状态是通过 httpProvider angular module app service httpResponseInterceptor q function q this respon
  • Node.js 开发人员的高级文档 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 最近我们的团队正在使用 Node js 开发一个新项目 开始使用 Node js 并不难 但现在我们才
  • 检查范围内唯一单元格的数量

    我有一张 Excel 表格 在 E 列下 我有 425 个包含数据的单元格 我想检查相同的数据 即单元格内的文本 是否在 E 列下剩余 424 个单元格中的任何其他位置重复 我该如何执行此操作 例如 在 E54 中我有 Hello Jack
  • UITextField 文本上的阴影

    是否可以在文本中添加阴影UITextField 从 3 2 开始 您可以使用 CALayer 阴影属性 textField layer shadowOpacity 1 0 textField layer shadowRadius 0 0 t
  • 错误:错误 1005:无法创建表“cat10e.recording”(错误号:150)[重复]

    这个问题在这里已经有答案了 我正在尝试对我的数据库进行正向工程 该数据库有 7 个表 但其中一个向我发送了错误 我真的不知道从这里做什么 因为它的设置就像我的其他表一样 所以我不确定是什么导致了错误 谷歌返回了许多不同的答案 专辑SQL p
  • 代码不适用于 matlab 中的图像处理

    我想在matlab中计算这个公式 m n d size img1 matrix1 sum abs img1 img2 a matrix1 m n b a 100 其中img1 img2是尺寸为512 512 3的两张图像 目标是获得单个数值
  • Linux 中断与轮询

    我正在开发一个带有 DSP 和 ARM 的系统 ARM上有一个linux操作系统 我有一个 DSP 向 ARM Linux 发送数据 在 Linux 中 有一个内核模块读取从 DSP 接收到的数据 内核模块被唤醒以读取数据 使用 DSP 和
  • Hadoop 减少多种输入格式

    我在 HDFS 中有两个数据格式不同的文件 如果我需要减少两个数据文件 那么作业设置会是什么样子 例如想象一下常见的字数统计问题 在一个文件中使用空格作为世界分隔符 在另一个文件中使用下划线 在我的方法中 我需要针对各种文件格式使用不同的映
  • 谷歌地图用多边形模拟折线

    几年前 我编写了一些代码 突出显示了 Google 地图上的一条路径 其中用户输入了宽度 用户确定突出显示的路径有多宽 以米为单位 这样他们就可以看到他们所覆盖的地面 例如草坪施肥等 我计算了距一个点的距离 并使用 Google 地图com
  • “你的意思?” Lucene.net 中的功能

    有人可以告诉我如何在 Lucene net 中实现 您是说 功能吗 Thanks 你应该调查一下拼写检查器 https svn apache org repos asf lucene lucene net trunk C 23 contri
  • PHP - 电子邮件验证[重复]

    这个问题在这里已经有答案了 可能的重复 电子邮件地址验证 https stackoverflow com questions 1025466 email address validation 你好 我有这个功能来验证电子邮件地址 funct
  • 仅当我省略 usePublicVapidKey 方法时,Firebase Cloud Messaging 的 getToken() 才有效,为什么?

    我在实施 Firebase for Firebase Cloud Messaging FCM 时遇到具体问题 正如您在下面的代码中看到的 messaging usePublicVapidKey
  • Android:无法转换为 java.lang.CharSequence

    我不知道我哪里出了问题 我试图在 recyclerView 中列出食谱的成分 但我无法让 onBindViewHolder 正常工作 无论我尝试过什么 下面是适配器代码以及 xml Recipe class 本质上我需要将 Recipe 类