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.
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
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);
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