【问题标题】:Android RecyclerView database remove itemAndroid RecyclerView 数据库删除项
【发布时间】:2016-10-05 09:41:01
【问题描述】:

我正在尝试从从 SQLite DB 填充的 RecyclerView 列表中删除项目并收到此错误:

java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1

我正在尝试使用的代码正在处理未从 SQLite 数据库填充的数据,但在这种情况下,它会在长按时崩溃。这是我的代码:

 @Override
    public void onBindViewHolder(RecHolder holder, final int position) {
        final Todo item = listData.get(position);

        final int currentPosition = position;
        final Todo infoData = listData.get(position);

        holder.container.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                removeData(infoData);
                return true;
            }
        });

    }

    private void removeData(Todo infoData) {
        int position = dbTodo.indexOf(infoData);
        dbTodo.remove(position);
        notifyItemRemoved(position);
    }

谁能帮我解决这个问题?

解决方案

我在removeData() 中弄乱了这个db.Todo,它应该是listData,就像在初始化中一样。

【问题讨论】:

    标签: java android sqlite android-recyclerview


    【解决方案1】:

    该错误表示在dbTodo 中找不到infoData - 因此indexOf 返回-1,因此在您的后续行中,您删除索引-1 处的某些内容(这显然超出了界限)。要消除此错误,您必须先检查 infoData 是否存在,然后再尝试删除它。

     private void removeData(Todo infoData) {
            int position = dbTodo.indexOf(infoData);
           //here you check that it exists before you try to remove it
            if(position >= -1){
             dbTodo.remove(position);
             notifyItemRemoved(position);
           }
          else{
              //do something else here?
           }
        }
    

    我希望这对你有帮助。

    【讨论】:

      【解决方案2】:

      很明显,您尝试从中获取项目的位置不正确。

      dbTodo.indexOf(infoData)
      

      如果没有找到 infoData 对象,则返回 -1,因此您必须选择: 1) 在尝试从数据库中删除对象之前检查位置

      if(position >= -1){
           dbTodo.remove(position);
           ......
      

      2) 在尝试删除之前检查 infoData 是否确实在数据库中。

      【讨论】:

        猜你喜欢
        • 2021-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-13
        • 2020-09-25
        • 2014-11-22
        • 1970-01-01
        相关资源
        最近更新 更多