How do I check if ringtone pointed by uri exists?
Asked Answered
C

2

5

I'm able to play a ringtone using the following code

rone = RingtoneManager.getRingtone(this.getContext(), Uri.parse(one));
rone.play();

How do I check if the audio file pointed by uri exists? When the user deletes a file from their phone, I'm not able to play the ringtone and it crashes.

Coaly answered 19/4, 2013 at 17:59 Comment(1)
check whether the rone is nullSigler
A
7

getRingtone() will return null if the ringtone does not exist.

Always check that a returned value is not null, this is a good practice whenever you call methods that might return null value. This will prevent a whole lot of NullPointerException

Avicenna answered 19/4, 2013 at 18:11 Comment(2)
Thanks, I was able to check if the ringtone exists by checking if (ringtone!=null){ //do something }else{ //no ringtone, do something else }Coaly
For some reason, I get a non-null object even though I've deleted its file in the ".../notifications" folder, and I also got a weird name for the ringtone (a number) instead of the original name.Naquin
M
1

Try to use getRingtonePosition() method instead of getRingtone():

final RingtoneManager rm = new RingtoneManager(preference.getContext());
final Uri loadedRingtoneUri = Uri.parse(ringtoneUriString);
final int pos = rm.getRingtonePosition(loadedRingtoneUri);

// if loaded ringtone uri is valid, use it or use default
final Ringtone ringtone = RingtoneManager.getRingtone(preference.getContext(),
                        (pos != -1) ? loadedRingtoneUri :
                                      Settings.System.DEFAULT_RINGTONE_URI);
Mercymerdith answered 10/10, 2015 at 19:31 Comment(2)
I'm getting a -1 even when the URI is a valid one and points to an existing file.Amarelle
Ah, I know why. You need this additional line after instantiating a RingtoneManager: rm.setType(RingtoneManager.TYPE_NOTIFICATION); OR pick whichever ringtone type your application is using. Ringtone manager needs to know what type of ringtones to load (use TYPE_ALL for all types).Amarelle

© 2022 - 2024 — McMap. All rights reserved.