Reputation: 91
I'm currently working on my A Level Computer Science Controlled Assessment, making a Scout Manager application in Android Studio, Java and XML, none of which I have used before. I'm now on the last stretch, but I've run into an error which I can't seem to solve.
I'm trying to delete a session record from the events table. This has worked perfectly fine before, however for some reason, despite no change in code (that I can remember, anyway), it no longer does.
Here is the code from the "Edit Event" activity:
//Deletes the event from the database
public void deleteEvent(View view)
{
boolean result=DatabaseHandler.deleteSession(sessionid);
if (result==true)
{
Toast.makeText(
context,
"Event Deleted",
Toast.LENGTH_SHORT
).show();
backToProgramme(view);
}
else
{
Toast.makeText(
context,
"Error - please try again",
Toast.LENGTH_SHORT
).show();
}
}
And here is the code from the databaseHandler:
//Deleting a session in the events table
public boolean deleteSession(int id)
{
boolean result = false;
String query = "SELECT * FROM " + TABLE_EVENTS + " WHERE " + COLUMN_SEID + " = '"
+ String.valueOf(id) + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
sessionDetails session = new sessionDetails();
if (cursor.moveToFirst())
{
session.setSessionID(Integer.parseInt(cursor.getString(0)));
db.delete (TABLE_EVENTS, COLUMN_SCID + "=?", new String[]{String.valueOf(
session.getSessionID())});
cursor.close();
result = true;
}
return result;
}
I can't at all work out why this isn't deleting the record.
Upvotes: 2
Views: 826
Reputation: 164064
What you are doing here is:
search the table TABLE_EVENTS
to find a row with COLUMN_SEID = id
and if found then get the value of column COLUMN_SCID
and delete the row where COLUMN_SCID
equals that value!
Why all this?
Can't you just delete the row with COLUMN_SEID = id
?
I believe that your code should be written like this:
public boolean deleteSession(int id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_EVENTS, COLUMN_SEID + " = ?", new String[]{String.valueOf(id)}) > 0;
}
The method delete()
returns the number of deleted rows, so deleteSession()
will return false
if no row was deleted.
Upvotes: 3