Удаление элемента из SQLite и listView

I want to delete item from a listView and SQLite database with contextMenu (press on item and hold, delete button appears, press it and item removes) and my code doesnt remove anything. Я попытался, когда нажал на Delete, тост с текстом появляется, и это сработало.

DBAdapter.Ява

public void delete(String name)throws SQLException {
        SQLiteDatabase db = helper.getWritableDatabase();
        if (db == null) {
            return;
        }
        String[] whereArgs = new String[] { name };
        db.delete("m_TB", "NAME"+ "=?", whereArgs);
        db.close();
    }

MainActivity.Ява

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add("Delete");
    }

    public boolean onContextItemSelected(MenuItem item) {
        super.onContextItemSelected(item);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        String name = info.toString();
        if (item.getTitle().equals("Delete")) {
            db.delete(name);
            books.remove(item);
            adapter.notifyDataSetChanged();

        }
        return true;
    }

ПОЛНЫЙ КОД:

MainActivity.Ява

public class MainActivity extends AppCompatActivity {


    ListView lv;
    EditText nameTxt;
    Button savebtn, retrievebtn;
    ArrayList<String> books = new ArrayList<String>();
    ArrayAdapter<String> adapter;
    SearchView sv;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
        private GoogleApiClient client;

        final DBAdapter db = new DBAdapter(this);

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            nameTxt = (EditText) findViewById(R.id.editText);

            savebtn = (Button) findViewById(R.id.saveBtn);
            retrievebtn = (Button) findViewById(R.id.retrieveBtn);

            lv = (ListView) findViewById(R.id.listView1);

            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, books);



            registerForContextMenu(lv);

            savebtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    db.openDB();
                    long result = db.add(nameTxt.getText().toString());

                    if (result > 0) {
                        nameTxt.setText("");
                    } else {
                        Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
                    }
                    db.close();
                }
            });
            retrievebtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    books.clear();
                    db.openDB();
                    Cursor c = db.getAllNames();

                    while (c.moveToNext()) {
                        String colIndex = c.getString(1);
                        books.add(colIndex);
                    }
                    lv.setAdapter(adapter);
                    db.close();
                }
            });
            lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(getApplicationContext(), books.get(position), Toast.LENGTH_SHORT).show();
                }
            });
            // ATTENTION: This was auto-generated to implement the App Indexing API.
            // See https://g.co/AppIndexing/AndroidStudio for more information.
            client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();



    }
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            menu.add("Delete");
        }

        public boolean onContextItemSelected(MenuItem item) {
            super.onContextItemSelected(item);
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
            String name = info.toString();
            if (item.getTitle().equals("Delete")) {
                books.remove(info.position);
                adapter.notifyDataSetChanged();

            }
            return true;
        }
    }

DBAdapter.Ява

public class DBAdapter {

    static final String ROW_ID ="id";
    static final String NAME ="name";
    static final String TAG = "DBAdapter";

    static final String DBNAME="m_DB";
    static final String TBNAME="m_TB";
    static final int DBVERSION='1';

    static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "name TEXT NOT NULL);";

    final Context c;
    SQLiteDatabase db;
    DBHelper helper;
    public DBAdapter(Context ctx) {
        this.c = ctx;
        helper = new DBHelper(c);
    }


    private static class DBHelper extends SQLiteOpenHelper {
        public DBHelper(Context context) {
            super(context, DBNAME, null, DBVERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL(CREATE_TB);
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w("DBAdapter","Upgrading DB");
            db.execSQL("DROP TABLE IF EXISTS m_TB");
            onCreate(db);
        }
    }
    public DBAdapter openDB()
    {
        try {
            db=helper.getWritableDatabase();
        } catch (SQLException e)
        {
            Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return this;
    }

    public void close()
    {
        helper.close();
    }

    public long add(String name)
    {
        try {
            ContentValues cv = new ContentValues();
            cv.put(NAME,name);
            return db.insert(TBNAME,ROW_ID,cv);
        } catch (SQLException e)
        {
            e.printStackTrace();
        }
        return 0;
    }

    public Cursor getAllNames()
    {
        String[] columns={ROW_ID,NAME};
        return db.query(TBNAME,columns,null,null,null,null,null);
    }

    public void delete(String name)throws SQLException
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        if(db == null)
        {
            return;
        }
        String[] whereArgs = new String[]{name};
        db.delete("m_TB", "NAME"+ "=?", whereArgs);
        db.close();
    }


}

1 ответ

  1. Вы не удаляете элемент из списка books. Если booksесть ArrayListто
    Измените строку кода на

    books.remove(info.position);
    

    И удалить из базы данных (если books является ArrayList пользовательского типа).

     db.delete(books.get(info.position).name);
    

    И если книги является arraylist строки, то

     db.delete(books.get(info.position));