当前位置: 首页 > 知识库问答 >
问题:

Android:无法转换为java。lang.CharSequence语言

郜俊晤
2023-03-14

我不知道我在这方面哪里出了问题,我正在尝试在recyclerView中列出食谱的成分,我只是无法让onBindViewHolder工作,不管我尝试了什么。下面是适配器代码以及xml配方。班本质上,我需要向recyclerView显示Recipe类的结果。

食谱班

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();
        }

    }
}

<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>  

适配器

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);
}

完整logcat

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)

RecipeList模型公共类RecipeList{

    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;
    }
}

更新的错误

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

在这一行:holder。myTextView。setText(itemRecipe.get(位置))。toString());

共有1个答案

王鹏飞
2023-03-14

在代码itemRecipe.get(位置)正在返回RecipeList这个对象,您将RecipeList直接传递到setText期望String的位置,尝试在此处传递String值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

前任:

holder.myTextView.setText(itemRecipe.get(position).toString)
 类似资料:
  • 我的customer.xsd如下所示。我正试图将它转换为pojo类schema_reference.4:未能读取模式文档“xml.xsd”,因为 1)找不到文件; 2)文件无法阅读; 3)文档的根元素不是。 我正在使用maven将XSD转换为Java clases。

  • 问题内容: 当我在本地主机中尝试时,它可以工作。这是我的本地主机提供的JSON。 是这个网址http://api.androidhive.info/contacts/中的错误 X 主要活动 错误 问题答案: 您可以尝试以下方法:

  • 这是我得到错误的代码 这是我的AnalyticsApplication类 这是logcat上的错误 03-09 18:46:11.070 32602-32602/auc。games2.multigame1 E/AndroidRuntime:致命异常:主java。lang.ClassCastException:android。应用程序。无法将应用程序转换为auc。游戏2.分析。auc的分析应用。ga

  • 我是JSON的新手,但我尝试使用所有的答案,但都不起作用。请帮帮我,我做错了什么。 } 我的JSON用于解析。

  • 我将客户数据对象存储为共享首选项(Android)中的JSON字符串,并尝试检索转换回客户对象的字符串并用于验证。从对象到JSON字符串的转换非常好,并且存储在首选项中(作为键值(字符串)对)。 当我尝试使用-我总是得到相同的错误值...类型java.lang.字符串不能转换为JSONObject。 我希望一双不同的眼睛能捕捉到我不能捕捉到的东西。带有数据的错误消息(屏蔽): Value 类型为j