0

I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.
Is there a good method or query to check if the UserId == ThreadId?

My current code:

public void deleteThread() {
    SQLiteDatabase db = this.getWritableDatabase();
    // Delete All Rows
    db.delete(TABLE_THREAD, null, null);
    db.close();

    Log.d(TAG, "Deleted all Thread info from sqlite");
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ajmoo
  • 3
  • 2
  • you mean equals? – Stultuske Nov 16 '17 at 14:03
  • 1
    What purpose would a check `UserId == ThreadId` serve exactly? Wouldn't it make more sense to just delete a specific `ThreadId`? You need to supply a Where clause as the second and third parameters in your `db.delete` method. See: [SQLiteDatabase delete method](https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete(java.lang.String,%20java.lang.String,%20java.lang.String[])) – OH GOD SPIDERS Nov 16 '17 at 14:06
  • Your code does exactly what you described because you're not narrowing down the `delete` query to an individual item. You're not even passing any sort of ID to the method so should not surprise you. – kryger Nov 16 '17 at 14:07
  • Possible duplicate of [Deleting Row in SQLite in Android](https://stackoverflow.com/questions/7510219/deleting-row-in-sqlite-in-android) – kryger Nov 16 '17 at 14:15

2 Answers2

1

You need to pass correct value to the well-documented delete method to narrow down the scope of deletion to a subset of all entries in the DB table.

public void deleteThreadById(String threadId) {
    SQLiteDatabase db = this.getWritableDatabase();
    String whereClause = "threadId = " + threadId;
    db.delete(TABLE_THREAD, whereClause, null);
    db.close();
}

Deleting all threads of a given user via their userId would be similar but probably doesn't make sense in a forum software.


This is how SQL works in general and it's a bit scary you started development without familiarising yourself with the very basics.

kryger
  • 12,906
  • 8
  • 44
  • 65
  • I actually fixed it yesturday with something like this. but i think i just did a bad example, srry guys, but thanks. And i will bee reading more about Sql, ihavent been working with sql for a while. Thanks – Ajmoo Nov 17 '17 at 06:41
1

Something like this;

public void deleteThread(String threadName) {
    SQLiteDatabase db = this.getWritableDatabase();
    try {
        db.delete(MYDATABASE_TABLE, "name = ?", new String[]{threadName});
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.close();
    }
}

Something long these lines, querying database to find the specific row that has column which matches the parameter.

For example to delete a row which the name column is "Hello World";

deleteThread("Hello World");