jmng
jmng

Reputation: 2568

Can't delete from MediaStore

I'm trying to replace the user's ringtone with an MP3 file. The ringtone file is generated on demand and its contents change; however, I need to guarantee that the filename and its title (that appears on the ringtone list) remain the same.

I can replace the ringtone once with no problem, the dificculties start when I try do add the ringtone for the second time, as ContentResolver.insert() returns a NullPointerException; from what I tested, this happens because there is already a file registered with the same values in the data or title columns (I still can't figure out which causes the problem, if they do indeed).

So I'm trying to delete the entry from the MediaStore, but without much success, because delete() returns 0 and the entries remain in the MediaStore. I've tried two things:

attempt #1 doesn't delete the entry

getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,"TITLE='TestRing'",null);

attempt #2 also doesn't delete the entry

final String[] ringColumns = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.TITLE,MediaStore.MediaColumns._ID };
final String ringOrderBy = MediaStore.Audio.Media._ID+" DESC";
final String ringWhere = MediaStore.Images.Media.TITLE+"=?";
final String[] ringArguments = { "TestRing" };

Cursor ringCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, ringColumns, ringWhere, ringArguments, ringOrderBy);

if(ringCursor.getCount()>1)
{
    while(ringCursor.moveToNext())
    {
        int id = ringCursor.getInt(ringCursor.getColumnIndex(MediaStore.Audio.Media._ID));            
        String title = ringCursor.getString(ringCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));            

        if(title.equals("TestRing"))
        {                
            ContentResolver cr = getContentResolver();
            retVal += cr.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStore.Audio.Media._ID + "="+id, null );
            break;
        }
    }               
}  

this is the code I use to create the entry in the media store, works fine if no entry exists:

File fOut = new File("/mnt/sdcard/media/audio/ringtones/newRingtone.mp3");
if(fOut.exists())
    fOut.delete();

ContentValues content = new ContentValues();
content.put(MediaStore.Audio.Media.IS_RINGTONE, true);
content.put(MediaStore.MediaColumns.DATA,fOut.getAbsolutePath());
content.put(MediaStore.MediaColumns.TITLE, "TestRing");       
content.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");

Uri uri = MediaStore.Audio.Media.getContentUriForPath(fOut.getAbsolutePath()); 
Uri newUri = getContentResolver().insert(uri, content); //insert returns null on the 2nd insertion

Upvotes: 2

Views: 1322

Answers (1)

jmng
jmng

Reputation: 2568

Solved, this code deletes previous entries with the same title:

getContentResolver().delete(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"TITLE='MyTitle'", null);

Upvotes: 2

Related Questions