Android is a simple way to delete the corresponding row information of the SQLite database by clicking the delete button corresponding to the listview entry.

After reading a lot of online information, the code to delete the corresponding row information in the database is very complicated. Here I provide a simple idea and code.

First, implement the click event of the button on the listview entry. In this method, call DeleteContentSQL(i) under databaseHelper to delete the database method. Here is the key. If you want to know the corresponding row, you must use the int i parameter in onItemClick to obtain the corresponding row.

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                view.findViewById(R.id.tcc).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {

                        EditText edit1 = (EditText) findViewById(R.id.name);
                        final String id=edit1.getText().toString();
                       String ret2= databaseHelper.DeleteContentSQL(i);//调用删除方法,i为条目行数
                       if(ret2.equals("1")) {
                           initview();
                           Toast.makeText(MassegeActivity.this, "删除成功", Toast.LENGTH_LONG).show();
                       }
                       else
                           Toast.makeText(MassegeActivity.this, "删除失败", Toast.LENGTH_LONG).show();
                    }


                });

            }


        });

 

In DeleteContentSQL(), call the databaseHelper class query() to query the database information. The key is, how to find the row of the database through the parameters sent by the main function. Call cursor.moveToPosition(i). This method only obtains the corresponding row of the database. Data, since there is only one row of data, you only need to obtain the ID number of another column to delete it. What needs to be noted is:

使用moveToPosition(i)一定要用if判断而不是while,否则会造成死循环。

The following is the DeleteContentSQL(int i) code:

 public  String DeleteContentSQL(int i) {
            String result = "";
            try {
                Cursor cursor = database.query("massege", null, null,
                        null, null, null,null);
                if (cursor.moveToPosition(i)) {
                    String id1 = cursor.getString(cursor.getColumnIndex(DBinfo._NO));
                    database.execSQL("delete from massege where ID = ?", new String[]{id1});
                    result = "1";
                }
            }
        catch (SQLException e)
        {
            e.printStackTrace();
            result += "查询数据异常!" + e.getMessage();
        }
return result;
    }

If you need the complete code, you can download it yourself:

Source code

                        

Guess you like

Origin blog.csdn.net/qq_45098495/article/details/107137727