我有一个用字符串值填充的简单列表视图,当用户长按特定项目时,他可以选择删除它(在上下文操作模式下)。列表视图中的值位于 sql 数据库中。我的“deleteCat”方法似乎不起作用。每当我尝试删除项目时,我都会遇到错误(“没有这样的列:*items_name*”)
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete_cat:
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
entry.deleteCat(itemClicked);
List<String> all = entry.getAllCategory();
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
entry.close();
mode.finish(); // Action picked, so close the CAB
return true;
数据库类:
公共类 CategoryDatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_CATEGORY = "category";
private static final String DATABASE_NAME = "DBCategory";
private static final String DATABASE_TABLE = "categoryTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public CategoryDatabase(Context c){
ourContext = c;
}
public CategoryDatabase open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CATEGORY + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long createEntry(String category) {
ContentValues cv = new ContentValues();
cv.put(KEY_CATEGORY, category);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public List<String> getAllCategory() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + DATABASE_TABLE;
Cursor cursor = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
List.add(cursor.getString(1));
} while (cursor.moveToNext());
}
return List;
}
public void deleteCat(String itemClicked) {
ourDatabase.delete(DATABASE_TABLE, KEY_CATEGORY + "=" + itemClicked, null);
}
}