Search code examples
androidringtone

Why my newUri from ContentValues is null? Setting ringtone programmatically


I'm trying to set the song as a ringtone. I have found a lot of ways to do it but nothing works. One of these ways looks as follows:

 private void setSongAsRingtone(Song song){
        File ringFile = new File(song.getPath());

        Log.d(tag, "Ring name: " + ringFile.getName());
        Log.d(tag, "Ring absolute path: " + ringFile.getAbsolutePath());
        Log.d(tag, "Activity: " + getActivity().toString());

        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, ringFile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, song.getTitle());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
        values.put(MediaStore.MediaColumns.SIZE, 26454);
        values.put(MediaStore.Audio.Media.ARTIST, song.getArtist());
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        values.put(MediaStore.Audio.Media.IS_ALARM, true);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        Uri uri = MediaStore.Audio.Media.getContentUriForPath(ringFile.getAbsolutePath());
        Uri newUri = getActivity().getContentResolver().insert(uri, values);
        RingtoneManager.setActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_RINGTONE, newUri);
    }

Logcat says:

D/RingtoneDialogFragment: Ring name: Jamal - Peron [Official Music Video].m4a
D/RingtoneDialogFragment: Ring absolute path: /storage/emulated/0/storage/emulated/0/Download/Jamal - Peron [Official Music Video].m4a
D/RingtoneDialogFragment: Activity: com.linkplayer.linkplayer.main.MainActivity@7bc8453
I/RingtoneManager: Save cache type :1, URI : content://0@media/external/audio/media/10557
W/RingtoneManager: Failed to open directly; attempting failover: java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
W/RingtoneManager: Failed to cache ringtone: java.io.IOException: java.lang.SecurityException: Uri is not ringtone, alarm, or notification: content://0@media/external/audio/media/10557
I/RingtoneManager: ringtone title : Jamal - Peron [Official Music Video], DRM : 0

But the newUri object is null and I have some errors. Maybe somebody has an idea why?

Thanks in advance for the help. Have a nice evening.


Solution

  • I had to call this method before inserting (creating newUri):

    String filePathToDelete = MediaStore.MediaColumns.DATA + "=\"" + ringtoneFile.getAbsolutePath() + "\"";
    getActivity().getContentResolver().delete(uri, filePathToDelete, null);