I made some simple project for test, but i'm having some trouble with delete. It won't work. I can add contact normally, but when I try to delete it, nothing happens and i don't have any erros. Here is my code:
Entity
@Entity
public class Contact {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @ColumnInfo(name = "contact_name")
    private String contactName;
    @ColumnInfo(name = "contact_number")
    private String contactNumber;
    @ColumnInfo(name = "contact_image")
    @Nullable
    private String contactImage;
...
My Dao:
@Dao
public interface ContactDao {
    @Query("SELECT * FROM Contact")
    LiveData<List<Contact>> getContacts();
    @Query("SELECT * FROM Contact WHERE id = :contact_id")
    Contact getContactById(int contact_id);
    @Insert
    void addContact(Contact contact);
    @Delete
    void deleteContact(Contact contact);
}
ViewModel:
public class ContactViewModel extends AndroidViewModel {
    private LiveData<List<Contact>> contacts;
    private ContactsDatabase contactsDatabase;
    public ContactViewModel(@NonNull Application application) {
        super(application);
        contactsDatabase = ContactsDatabase.getINSTANCE(this.getApplication());
        contacts = contactsDatabase.contactDao().getContacts();
    }
    public LiveData<List<Contact>> getContacts() {
        return contacts;
    }
    public void deleteContact(Contact contact) {
        new deleteAT(contactsDatabase).execute(contact);
    }
    private class deleteAT extends AsyncTask<Contact, Void, Void> {
        private ContactsDatabase contactsDatabase;
        deleteAT(ContactsDatabase db) {
            this.contactsDatabase = db;
        }
        @Override
        protected Void doInBackground(Contact... contacts) {
            contactsDatabase.contactDao().deleteContact(contacts[0]);
            return null;
        }
    }
}
Any solutions ?
In some cases it might be better to add a custom delete by-id instead of using the auto-generated delete by-object.
In this case it'd be
    @Query("DELETE FROM Contact WHERE id = :contact_id")
    void deleteContactById(int contact_id);
See https://stackoverflow.com/a/47554641/6513193 for more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With