ClassCastException:String 无法转换为

ClassCastException:String cannot be cast to

我的代码有错误。

logcat:

java.lang.ClassCastException: java.lang.String cannot be cast to com.example.aymen.schoolmanager.dates at com.example.aymen.schoolmanager.Adapter.onBindViewHolder(Adapter.java:68) at com.example.aymen.schoolmanager.Adapter.onBindViewHolder(Adapter.java:20) at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6356) at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6389) at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5335) at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5598) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5440) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5436) at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312) at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1795) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131) at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42) at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1391) at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:870) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) at android.widget.FrameLayout.onLayout(FrameLayout.java:261) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585) at android.widget.LinearLayout.onLayout(LinearLayout.java:1494) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) at android.widget.FrameLayout.onLayout(FrameLayout.java:261) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585) at android.widget.LinearLayout.onLayout(LinearLayout.java:1494) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) at android.widget.FrameLayout.onLayout(FrameLayout.java:261) at com.android.internal.policy.DecorView.onLayout(DecorView.java:726) at android.view.View.layout(View.java:17637) at android.view.ViewGroup.layout(ViewGroup.java:5575) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068) 06-22 10:11:41.107 22646-22646/com.example.aymen.schoolmanager E/AndroidRuntime: at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6337) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874) at android.view.Choreographer.doCallbacks(Choreographer.java:686) at android.view.Choreographer.doFrame(Choreographer.java:621) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

第 68 行指向:

holder.textViewHead.setText(idd.get(position).getSubject());

第 20 行指向:

class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>

这是我的代码:

我的数据库class处理程序:

public class DBhandler extends SQLiteOpenHelper {
    private static final String databas_name="newdata.db";
    public static final int databas_version=1;
    public static String ID="id";
    int id;
    SQLiteDatabase dj;
    ArrayList<dates> er=new ArrayList<dates>();
    SQLiteDatabase db;
    DBhandler helper;
    String TYPE="type";
    String sub="Subject";
    String Title="Title";
    String det="Detail";
    String TabN="ClassExams";
    int i;

    public DBhandler(Context context)
    {
        super(context,databas_name,null,databas_version);
    }




    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE if not EXISTS ClassExams(id INTEGER primary key,type TEXT,Subject TEXT,Title TEXT,Detail TEXT) ");
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP table if EXISTS ClassExams");
        onCreate(db);

    }



    public void insert(String type, String sub, String title, String detaill)
    {
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues contentValues=new ContentValues();
        contentValues.put("type",type);
        contentValues.put("Subject",sub);
        contentValues.put("Title",title);
        contentValues.put("Detail",detaill);
        db.insert("ClassExams",null,contentValues);
        db.close();



     }


    public ArrayList getAs(String Type)
    {


        String DATABASE_TABLE="ClassExams";
        String type="type";
        String quer = "SELECT * FROM " + DATABASE_TABLE + " WHERE " + type + "='" + Type+"'";
        ArrayList arrayList=new ArrayList();
        SQLiteDatabase db=this.getReadableDatabase();

        Cursor res=db.rawQuery(quer,null);
        res.moveToFirst();
        while (res.isAfterLast()==false){
            arrayList.add(res.getString(res.getColumnIndex("id")));

            //  arrayList.add(res.getString(res.getColumnIndex("Subject")));
            // arrayList.add(res.getString(res.getColumnIndex("Title")));
            // arrayList.add(res.getString(res.getColumnIndex("Detail")));
            res.moveToNext();

        }
        return arrayList;

    }


    public void deleteNote(int x){
        String TABLE_NAME="ClassExams";
        String ID="id";
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, ID + " = ?",new String[] {String.valueOf(x)});
    }





} 

我的适配器class:

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
    Context activity;
    private ArrayList<dates> idd;

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textViewHead;
        public TextView textViewDown;
        public TextView buttonViewOption;
        public int position;
        public ViewHolder(View itemView) {
            super(itemView);

            textViewHead = (TextView) itemView.findViewById(id.text1);

            textViewDown = (TextView) itemView.findViewById(id.text2);

            buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
        }
    }


    public Adapter (Context context, ArrayList<dates> id) {
      this.activity=context;
         this.idd=id;

    }
    @Override
   public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater=LayoutInflater.from(activity);
      //  View row=inflater.inflate(layout.costum_row,parent,false);
        View view = LayoutInflater.from(parent.getContext()).inflate(layout.costum_row, null);

        ViewHolder holder=new ViewHolder(view);
        return holder;
    }
    public void onBindViewHolder(final Adapter.ViewHolder holder, final int position) {
        //  dates object=idd.get(position);
        // String firstText = object.getDetail();
        // String secondText = object.getSubject();


        holder.textViewDown.setText("Somthing");
        holder.textViewHead.setText(idd.get(position).getSubject());
        holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                PopupMenu popup = new PopupMenu(activity, holder.buttonViewOption);

                popup.inflate(R.menu.option_menu);

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {

                        switch (item.getItemId()) {
                            case id.Update:

                                break;
                            case R.id.menu2:

                                break;
                            case id.Delete:

                                delete();
//db.deleteNote(Integer.parseInt(j));

                                // db.deleteNote(getid);
                        }
                        return false;
                    }
                });
                //displaying the popup
                popup.show();
            }

            public void delete() {
                idd.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, idd.size());
                holder.itemView.setVisibility(View.GONE);
            }

        });
    }

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

我的class:

public class dates {
    String Subject,Title,Detail,type;
     int id;

    public dates(String subject, String title, String detail, String type, int id) {
        this.Subject = subject;
        this.Title = title;
        this.Detail = detail;
        this.type = type;
        this.id = id;
    }

    dates()
    {

    }


    public String getSubject() {
        return Subject;
    }

    public  void setSubject(String subject) {
        Subject= subject;
    }

    public String getTitle() {
        return Title;
    }

    public void setTitle(String title) {
        Title = title;
    }

    public String getDetail() {
        return Detail;
    }

    public void setDetail(String detail) {
        Detail = detail;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getId() {
        return id;
    }

    public void seti(int id) {
        this.id = id;
    }

这里没有显示所有必要的代码,但我假设来自 ArrayList DBHandler.getAs() 的数组列表作为 id 参数传递给 Adapter constuctor

public Adapter (Context context, ArrayList<dates> id)

应该有关于 "unchecked or unsafe operations" 的编译器警告。

什么 getAs returns 实际上是一个包含 String 个对象的列表,现在被解释为一个包含 dates 个对象的列表,这导致 class 一旦访问其中一个元素就会抛出异常。

从中可以吸取两个教训:

  1. 不要忽略编译器警告
  2. 不要使用原始集合 classes