SQLite删除项

时间:2016-04-29 16:52:48

标签: android sqlite listview

我想知道,如何从listview和SQLite数据库中删除项目。我有这个代码。我应该更改什么,因为项目没有从列表视图中删除。这是我的整个代码,我不知道该改变什么

DBAdapter.java

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);
}

MainActivity.java

public class MainActivity extends AppCompatActivity {


    ListView lv;
    EditText nameTxt;
    Button savebtn,retrievebtn;
    ArrayList<String> books = new ArrayList<String>();
    ArrayAdapter<String> adapter;

    @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_selectable_list_item,books);
        final DBAdapter db = new DBAdapter(this);

        savebtn.setOnClickListener(new View.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 View.OnClickListener() {
            @Override
            public void onClick(View v) {
                books.clear();
                db.openDB();
                Cursor c = db.getAllNames();

                while (c.moveToNext())
                {
                    String name = getString(1);
                    books.add(name);
                }
                lv.setAdapter(adapter);
                db.close();
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getApplicationContext(),books.get(position), Toast.LENGTH_SHORT).show();
            }
        });
    }


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);

        if(item.getTitle()== "Delete")
        {
            books.remove(item);
            adapter.notifyDataSetChanged();
        }
        return true;
    }

我将其插入DPAdapter

public void delete(String name)throws SQLException {
        SQLiteDatabase db = helper.getWritableDatabase();
        if (db == null) {
            return;
        }
        String[] whereArgs = new String[] { name };
        db.delete(TBNAME, 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;
    }

但没有发生任何事情。我怎么称呼删除方法?

2 个答案:

答案 0 :(得分:1)

将字符串与.equals比较而不是&#34; ==&#34; :

if(item.getTitle().equals("Delete"))
        {
            books.remove(item);
            adapter.notifyDataSetChanged();
        }

您还需要添加删除查询以从SQlite中删除项目,因为您目前只从列表视图中删除项目。

答案 1 :(得分:1)

这是您从SQLite Database删除项目的方法,您需要将其添加到DBAdapter

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

并从ListView中删除它,您需要从列表中删除项目,然后通知您的适配器

YourArraylist.remove([index]);
YourAdapter.notifyDataSetChanged();