“如何在sqlite数据库中清除正确的listview项目

时间:2019-06-12 12:56:50

标签: java android sqlite listview

我要从数据库中删除列表视图项,如何正确链接其数据库项的每个列表项?

我已经尝试删除_id是列表位置的位置,但是每次都无法正常工作。

这是我的适配器类上实现侦听器的viewholder类和getView方法

  private class ViewHolder{
        ImageView imageView;
        TextView nom;
        Button actualizar,borrar;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        View fila=view;
        ViewHolder holder=new ViewHolder();


        if(fila==null)
        {
            LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            fila=inflater.inflate(layout,null);
            holder.imageView=fila.findViewById(R.id.imagencoche);
            holder.nom=fila.findViewById(R.id.nombreCoche);
            holder.actualizar=fila.findViewById(R.id.btnAct);
            holder.borrar=fila.findViewById(R.id.btnBorrar);

            holder.borrar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyOpenHelper db=new MyOpenHelper(context);
                    db.borrarCoche(position+1+"");

                    lista=db.selectCoches();
                    notifyDataSetChanged();


                }
            });

            fila.setTag(holder);
        }
        else{
            holder=(ViewHolder)fila.getTag();

        }
        Coche coche=lista.get(position);


        holder.nom.setText(coche.getNombre());
        holder.imageView.setImageBitmap(coche.getFoto());

                return fila;
    }


从SQLite帮助器调用的2个方法

 public  void borrarCoche(String id)
    {

        String where="_id=?";
       SQLiteDatabase db=this.getWritableDatabase();

         db.delete("coches",where,new String[]{id});
    }

 public ArrayList<Coche> selectCoches(){
        ArrayList<Coche> lista =new ArrayList<Coche>();

        SQLiteDatabase db=this.getReadableDatabase();
        Cursor c =db.rawQuery("SELECT nombre, foto, longitud, latitud,_id from coches", null);

        if (c.moveToFirst()){
            do {
                //recogemos valores
                String nom = c.getString(0);
                byte[] foto = c.getBlob(1);
                float longitud = c.getFloat(2);
                float latitud = c.getFloat(3);
                int id = c.getInt(4);
                Coche coche = new Coche(id, longitud, latitud, DbBitMapUtility.getImage(foto), nom);
                lista.add(coche);


            }while(c.moveToNext());


        }

        return lista;

    }

它不能总是正常工作,有时会擦除另一个条目,或者当只剩下2或1时,它什么也不擦除。

2 个答案:

答案 0 :(得分:0)

第一件事,我不认为每次删除项目时都需要从数据库中调用这些项目。相反,您可以从数据库中删除该项目,然后从列表中将其删除,然后调用notifyDatasetChanged()。

此外,不要在getView()方法中调用侦听器,而应在ViewHoder类或onBindViewHolder()中调用此方法。因此,逻辑将类似于:

public class MyViewHolder extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView nom;
    Button actualizar,borrar;

    public MyViewHolder(View view) {
        super(view);
        holder.imageView=fila.findViewById(R.id.imagencoche);
        holder.nom=fila.findViewById(R.id.nombreCoche);
        holder.actualizar=fila.findViewById(R.id.btnAct);
        holder.borrar=fila.findViewById(R.id.btnBorrar);
    }
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.movie_list_row, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Coche coche = cocheList.get(position); //Where ArrayList<Coche> cocheList;
    holder.nom.setText("demo text");

    holder.borrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyOpenHelper db=new MyOpenHelper(context);
                db.borrarCoche(cocheList.getId()); //Don't use position as this is not id rather this is item index value.

                cocheList.remove(position);
                notifyDataSetChanged();
            }
        });
}

希望您会得到解决方案。

为了更好地理解,您可以按照https://www.androidhive.info/2016/01/android-working-with-recycler-view/来获得有关Android中RecyclerView的基本知识。

答案 1 :(得分:0)

问题是您在阵列中没有选择ID的ID。我使用它,可以尝试以下操作:

用于删除数据的SQLite代码:

public void borrarCoche(int id){
        this.openWriteableDB();
        String where = ConstantsBD.CAR_ID + " = ?";
        db.delete(ConstantsBD.TABLA_COCHES, where, new String[]{String.valueOf(id)});
        this.closeDB();
    }

Sqlite代码数组:

public ArrayList selectCoches() {
        ArrayList list = new ArrayList<>();
        this.openReadableDB();
        String[] campos = new String[]{ConstantsBD.COCHE_ID, //ConstantsBD is a Class where i create the sqlite tables
                ConstantsBD.NOM, ConstantsBD.FOTO,
                ConstantsBD.LONGITUD,ConstantsBD.LATITUD};
        Cursor c = db.query(ConstantsBD.TABLA_COCHES, campos, null, null, null, null, null);
        try {
            while (c.moveToNext()) {
                Coches coches=new Coches();
                ic.setIdCoche(c.getInt(0));//Your id always be in zero
                ic.setNombre(c.getString(1));
                ic.setFoto(c.getBlob(2));
                ic.setLongitud(c.getFloat(3));
                ic.setLatitud(c.getFloat(4));
                list.add(coches);
            }
        } finally { c.close(); }
        this.closeDB();
        return list;
    }

以及活动中ListView的代码:

ListView listView;
ArrayList<Coches> arrayCoches;
SQLITEDB conn;

public void onResume(){
super.onResume(); 
listView = (ListView)findViewById(R.id.lvCoches);
arrayCoches = new ArrayList<Coches>();
conn = new SQLITEDB(getApplicationContext());
arrayCoches=conn.selectCoches();
adt =new adapterCoches(YourActivityName.this, arrayCoches);
lvCam.setAdapter(adt);
lvCam.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,final  int position, long id) {
                AlertDialog.Builder alertbox = new AlertDialog.Builder(YourActivityName.this)
                        .setTitle("¡Alert!")
                        .setPositiveButton("Erase", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface arg0, int arg1) {
                                SQLITEDB bd = new SQLITEDB(getApplicationContext());
                                bd.borrarCoche(arrayCoches.get(position).getIdCoches() );
                                onResume();
                            }
                        })
                        .setNegativeButton("Update", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface arg0, int arg1) {
                            }
                        });
                alertbox.show();
            }
}