Dodi
Dodi

Reputation: 2269

Deleting from SQL database android

I have a list view and when the user clicks a specific item a contextual action mode is displayed with only one item in it (that is supposed to delete it). However, when I click it, the database is not updated (the item is still on the list). Could anyone help me ?

In MainActivity:

final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
protected Object mActionMode;
int catPos;


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

    CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
    entry.open();

    List<String> all = entry.getAllCategory();
    if(all.size()> 0){    
        lv = (ListView)findViewById(R.id.listView1);
        arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
        lv.setAdapter(arrayAdapter);
    }else{
       Toast.makeText(MainActivity.this,"No items to display",Toast.LENGTH_LONG).show();
    } 
    entry.close();

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
            int position, long id) {

          catPos = position;

          if (mActionMode != null) {
            return false;
          }

          // Start the CAB using the ActionMode.Callback defined above
          mActionMode = MainActivity.this
              .startActionMode(mActionModeCallback);
          view.setSelected(true);
          return true;
        }
      });


}

 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_delete_cat:
               // shareCurrentItem();
                CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
                entry.open();
                entry.deleteCat(catPos);

                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;
            default:
                return false;
        }
    }

in Actual Database:

public class 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(int catPos) {
    ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + catPos, null);     
}  

}

Upvotes: 0

Views: 160

Answers (1)

Opiatefuchs
Opiatefuchs

Reputation: 9870

Deleting as "entry.deleteCat(catPos);" is not right. If You use Your catPos, which is the position inside the listView, it will not delete the entry from database. You made an INTEGER_PRIMARY_KEY_AUTOINCREMENT inside Your Database, so this Integer will generated automatically and can differ from Your position Integer. What You have to do is, to make a query method inside Your Database where You get even the ID from Your DB-Entry. Then You could call

   entry.deleteCat(databaseId);

Upvotes: 1

Related Questions