dimanche 10 janvier 2016

Not able to delete a row in the database - Android Content Provider

I’m trying to write a method that deletes a row from the database table. The row contains information about a specific song that a user has selected.

I have a list of songs in a gridview where when a user clicks one of the items from the list the app will take them to my SongDetailFragment activity which contains more information about the song and I also have a star button where if a song in in the database the star button is switch On, and if it’s NOT in the database the star button is switch Off

When a user click the star button I'm able to add a song successfully in the database, but the problem is when they hit the same button again I’m suppose to delete the song in the database but it’s not deleting. It looks like suspect my deleteFromDB() method is not working correctly and I’m not sure what is the correct syntax to fix it.

Here is my method:

 private void deleteFromDB() {

        ContentValues songValues = new ContentValues();


        getActivity().getContentResolver().delete(SongContract.songEntry.CONTENT_URI,
                SongContract.songEntry.COLUMN_TITLE + " = ?",
                new String[]{songValues.getAsString(song.getTitle())});

      //switch off button
        imgViewFavButton.setImageResource(android.R.drawable.btn_star_big_off);
    }

Here is my delete snipper from my Provider:

@Override
    public int delete(Uri uri, String selection, String[] selectionArgs){
        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        final int match = sUriMatcher.match(uri);
        int numDeleted;
        switch(match){
            case SONG:
                numDeleted = db.delete(
                        SongContract.SONGEntry.TABLE_NAME, selection, selectionArgs);
                // reset _ID
                db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
                        SongContract.SONGEntry.TABLE_NAME + "'");
                break;
            case SONG_WITH_ID:
                numDeleted = db.delete(SongContract.SONGEntry.TABLE_NAME,
                        SongContract.SONGEntry._ID + " = ?",
                        new String[]{String.valueOf(ContentUris.parseId(uri))});
                // reset _ID
                db.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" +
                        SongContract.SONGEntry.TABLE_NAME + "'");

                break;
            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }

        return numDeleted;
    }

Aucun commentaire:

Enregistrer un commentaire