从SQLite和listView中删除项目

时间:2016-05-02 13:12:00

标签: android sqlite listview

我想用contextMenu从listView和SQLite数据库中删除项目(按下项目并按住,删除按钮,按下它和项目删除),我的代码不会删除任何内容。我尝试按下删除时,会出现带有文字的吐司并且它有效。

DBAdapter.java

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.java

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.java

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.java

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 个答案:

答案 0 :(得分:0)

您没有从列表books中删除该项目。如果booksArrayList,那么 将您的代码行更改为

books.remove(info.position);

从数据库中删除(如果books是自定义类型的ArrayList)。

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

如果书籍是字符串的arraylist那么

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