在 Android 中删除 ListiView 和 SQLite 行

Posted

技术标签:

【中文标题】在 Android 中删除 ListiView 和 SQLite 行【英文标题】:Delete ListiView and SQLite row in Android 【发布时间】:2019-11-07 20:52:57 【问题描述】:

我正在使用这个库在 android Studio 中开发一个应用程序:com.daimajia.swipelayout:library:1.2.0@aar。我的应用用户使用具有以下类的 SQLite 数据库:

BDSQLiteHelper.java

public class BDSQLiteHelper extends SQLiteOpenHelper 

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "ExtraOficial";
    private static final String TABELA_VAZAMENTOS = "VazamentosToSQL";

    private static final String vazID = "VazID";
    private static final String nomeServico = "nomeServico";
    private static final String[] VAZ_COLUNAS = vazID, nomeServico;

 public BDSQLiteHelper(Context context) 
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    

@Override
    public void onCreate(SQLiteDatabase db) 
String CREATE_VAZAMENTOTABLE = "CREATE TABLE VazamentosToSQL ("+
                "vazID          INTEGER PRIMARY KEY AUTOINCREMENT,"+
                "nomeServico)";
        db.execSQL(CREATE_VAZAMENTOTABLE);
 

@Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) 
        db.execSQL("DROP TABLE IF EXISTS VazamentosToSQL");
        this.onCreate(db);

    
public void addVazamentos(VazamentosToSQL VazamentosToSQL) 
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(nomeServico, VazamentosToSQL.getNomeServico());
        db.insert(TABELA_VAZAMENTOS, null, values);
        db.close();
    
public VazamentosToSQL getVazamentos (int vazID) 
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABELA_VAZAMENTOS,
                VAZ_COLUNAS,
                " vazID = ?",
                new String[] String.valueOf(vazID),
                null,
                null,
                null,
                null);
        if (cursor == null) 
            return null;
         else 
            cursor.moveToFirst();
            VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
            return VazamentosToSQL;
        
    


private VazamentosToSQL cursorTovazamentos(Cursor cursor) 
        VazamentosToSQL VazamentosToSQL = new VazamentosToSQL();
        VazamentosToSQL.setVazID(Integer.parseInt(cursor.getString(0)));
        VazamentosToSQL.setNomeServico(cursor.getString(1));
        return VazamentosToSQL;
    


public ArrayList<VazamentosToSQL> getAllVazamentos() 
        ArrayList<VazamentosToSQL> listaVazamentos = new ArrayList<VazamentosToSQL>();
        String query = "SELECT * FROM " + TABELA_VAZAMENTOS + " ORDER BY "+ vazID + " DESC";

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);

        if (cursor.moveToFirst()) 
            do 
                VazamentosToSQL VazamentosToSQL = cursorTovazamentos(cursor);
                listaVazamentos.add(VazamentosToSQL);
             while (cursor.moveToNext());

        
        return listaVazamentos;
    

[...]

public int deleteVazamentos(VazamentosToSQL VazamentosToSQL) 
        SQLiteDatabase db = this.getWritableDatabase();

        int i = db.delete(TABELA_VAZAMENTOS,
                vazID+" =?",
                new String[]  String.valueOf(VazamentosToSQL.getVazID()));
        db.close();
        return i;
    

VazamentosToSQL.java

public class VazamentosToSQL 
    private int vazID;
    private String nomeServico;
  public int getVazID()  return vazID; 
    public void setVazID(int vazID) 
        this.vazID = vazID;
    


    public String getNomeServico()  return nomeServico; 
    public void setNomeServico(String nomeServico)  this.nomeServico = nomeServico; 


ListViewActivity.java:

[...]
//variables
private BDSQLiteHelper bd;
ArrayList<VazamentosToSQL> listaVazamentos;
SwipeLayout swipeLayout;
private final static String TAG = ListViewActivity.class.getSimpleName();
vazamentosAdapter adapter;
ListView lista;
[...]
@Override
    protected void onCreate(Bundle savedInstanceState) 
super.onCreate(savedInstanceState);

[...]

 bd = new BDSQLiteHelper(this);
        lista = (ListView) findViewById(R.id.lvdenuncias);
        listaVazamentos = bd.getAllVazamentos();
        setListViewHeader();
        setListViewAdapter();

lista.setOnItemClickListener(new AdapterView.OnItemClickListener()  //aqui é o vazamentosAdapter
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) 
                Intent intent = new Intent(ExibeVazamentosActivity.this, DetalhesVazamentosActivity.class);
                intent.putExtra("vazID", listaVazamentos.get(position).getVazID());
                startActivity(intent);

            
        );
@Override
    protected void onStart() 
        super.onStart();
        updateAdapter(); //Refresh ListView items

    
private void setListViewHeader() 
        LayoutInflater inflater = getLayoutInflater();
        View header = inflater.inflate(R.layout.header_listview, lista, false);
        totalClassmates = (TextView) header.findViewById(R.id.total);
        swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
        setSwipeViewFeatures();
        //UNNECESSARY for me: lista.addHeaderView(header);
    
private void setSwipeViewFeatures() 
        swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);

        //add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
        swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));

        swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() 
            @Override
            public void onClose(SwipeLayout layout) 
                Log.i(TAG, "onClose");
            

            @Override
            public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) 
                Log.i(TAG, "on swiping");
            

            @Override
            public void onStartOpen(SwipeLayout layout) 
                Log.i(TAG, "on start open");
            

            @Override
            public void onOpen(SwipeLayout layout) 
                Log.i(TAG, "the BottomView totally show");
            

            @Override
            public void onStartClose(SwipeLayout layout) 
                Log.i(TAG, "the BottomView totally close");
            

            @Override
            public void onHandRelease(SwipeLayout layout, float xvel, float yvel) 
                //when user's hand released.
            
        );
    

private void setListViewAdapter() 
          adapter = new vazamentosAdapter(this, listaVazamentos);
          lista.setAdapter(adapter);
    


    public void updateAdapter() 
        listaVazamentos.clear();
        listaVazamentos.addAll(bd.getAllVazamentos());
        adapter.notifyDataSetChanged(); //update adapter
        lista.invalidateViews();
        lista.refreshDrawableState();
    

vazamentosAdapter.java:

public class vazamentosAdapter extends ArrayAdapter<VazamentosToSQL> 
    private final Context context;
    private final ArrayList<VazamentosToSQL> elementos;
    File imgFile;
    private Bitmap bitmap;
    private ExifInterface exifObject;
    private ExibeVazamentosActivity activity;
    int vazID;
    private SQLiteDatabase bd;

public vazamentosAdapter(Context context, ArrayList<VazamentosToSQL> elementos) 
        super(context, R.layout.linha, elementos);
        this.context = context;
        this.elementos = elementos;

    
@Override
    public View getView(int position, View convertView, ViewGroup parent) 
        ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) 
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.linha, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            convertView.setTag(holder);
        else 
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        
[...]
editText.setText(elementos.get(position).getVaznomeServico());

 holder.btnEdit.setOnClickListener(onEditListener(position, holder));
        holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));

        return convertView;
    

private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) 
        return new View.OnClickListener() 
            @Override
            public void onClick(View v) 

            /**--------------Tried it, not working =( ---------------*/
                elementos.get(position).getVazID(); 
               //listaVazamentos.remove(position); 
                //activity.listaVazamentos.remove(position); 
                //bd = context.openOrCreateDatabase("DesoExtraOficial", Activity.MODE_PRIVATE, null);
                //bd.execSQL("DELETE from VazamentosToSQL where vazID = '" + elementos.get(position).getVazID() + "'");
                //bd.close();



                //elementos.remove(position);
                Toast.makeText(context, "ID: "+elementos.get(position).getVazID(),Toast.LENGTH_LONG).show();
                bd.deleteVazamentos(VazamentosToSQL);



                holder.swipeLayout.close();
//                activity.updateAdapter(); //Executa o método "updateAdapter()" na Activity "ExibeVazamentos"
        /**--------------Tried it, not working =( ---------------*/
            
        ;
    


private class ViewHolder 
        private TextView name;
        private View btnDelete;
        private View btnEdit;
        private SwipeLayout swipeLayout;
        private ListView listv;

        public ViewHolder(View v) 
            swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
            btnDelete = v.findViewById(R.id.delete);
            btnEdit = v.findViewById(R.id.edit_query);
            listv = (ListView) v.findViewById(R.id.lvdenuncias);
            swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);
        
    

上述库运行良好。但是当用户根据列表视图选择的行单击按钮时,我试图删除数据库行。使用以下代码: elementos.get(position).getVazID() 我得到了数据库索引。但我无法从数据库中删除。有人可以帮我编写从数据库中删除行和从列表视图中删除行的代码吗?

【问题讨论】:

您必须在单击按钮时运行数据库删除查询 【参考方案1】:

尝试改变这个:

public int deleteVazamentos(VazamentosToSQL VazamentosToSQL)  
    SQLiteDatabase db = this.getWritableDatabase(); 
    int i = db.delete(TABELA_VAZAMENTOS, vazID+" =?", new String[]  String.valueOf(VazamentosToSQL.getVazID())); 
    db.close(); 
    return i; 

到这里:

public void deleteVazamentos(int vazID)  
    SQLiteDatabase db = this.getWritableDatabase(); 
    db.delete(TABELA_VAZAMENTOS, "vazID=" + vazID, null); 

然后如果你想删除一行,你可以调用: (内onDeleteListener

bd.deleteVazamentos(elementos.get(position).getVazID());

【讨论】:

你好 HB。持有人仅在 Dot 之后显示 btnDelete、btnEdit、listv、name 和 swipeLayout 选项。持有人选项: 谢谢你!效果很好。还有一件事,如何删除listview oDeleteListener 方法的对应项并更新listview 状态?当我使用方法 Activity.updateAdapter() 得到错误:尝试调用虚拟方法 [...] 在 Bull 对象上。 要调用该方法,您必须创建一个接口

以上是关于在 Android 中删除 ListiView 和 SQLite 行的主要内容,如果未能解决你的问题,请参考以下文章

如何在列表视图中的两个图像之间留出空间?

带有图像选择和取消选择的 Horizo​​ntalListview

在TabLayout(材料设计)android中动态添加和删除标签

如何在 Android 中删除和重命名文件?

android中每行中带有添加和删除按钮的ListView

Android,删除列表和sqlite java中的项目