Search code examples
androidandroid-4.2-jelly-beanringtone

Android Ringtone Play crash on 4.2


I am having problems playing a ringtone on my Nexus 4 running Android 4.2.

When I try and play a RingTone I see the following exception:

java.lang.NullPointerException at android.media.Ringtone.play(Ringtone.java:228)

My code is below:

RingtoneManager ringtoneManager = new RingtoneManager(context);
ringtoneManager.setType(AudioManager.STREAM_NOTIFICATION);
Ringtone ringtone = ringtoneManager.getRingtone(index);
Ringtone ringtone.setStreamType(AudioManager.STREAM_NOTIFICATION);

if (ringtone != null)
{
    ringtone.play();
}

The index value is passed into my method based on a user selection (I present them with the list of ringtones to select). In any case it makes no difference what I set this to the behaviour is always the same.

This code works perfectly when running on my two other devices running 2.3 and 4.0.4.

When I debug I can see that the uri is null in the Ringtone that is returned by the ringtone manager (and is set to a valid value on my other devices).

Am I doing something wrong or could this be a bug in 4.2?


Solution

  • I guess you need to check first if the ringtone exists at the position. So try

    Edit: try this.

    RingtoneManager ringtoneManager = new RingtoneManager(ActivityName.this);
    ringtoneManager.setType(AudioManager.STREAM_NOTIFICATION);
    Cursor c = ringtoneManager.getCursor();
    Ringtone ringtone = ringtoneManager.getRingtone(index);
    ringtone.setStreamType(AudioManager.STREAM_NOTIFICATION);
    if(ringtone != null && ringtoneManager.getRingtoneUri(position) != null){    
        ringtone.play();
    }