Search code examples
javaandroidringtone

Why does adding an empty for loop fix this code?


I am trying to play a ringtone selected by the user.

When I use this code:

RingtoneManager ringtoneManager = new RingtoneManager(this);
Uri uri = ringtoneManager.getRingtoneUri(position);

if(uri == null) {
    Log.d("ALARM", "uri is null");
}

try {
    mediaPlayer.setDataSource(getApplicationContext(), uri);
    mediaPlayer.prepare();  
    mediaPlayer.setLooping(true);
    mediaPlayer.start();
} catch (Exception e) {
    // Handle exception
}

I get "uri is null" and nothing happens, however if I put in an empty for loop beforehand like this:

for(int i = 0; i < ringtoneManager.getCursor().getCount(); ++i) {
//WTF
}

RingtoneManager ringtoneManager = new RingtoneManager(this);
Uri uri = ringtoneManager.getRingtoneUri(position);

if(uri == null) {
    Log.d("ALARM", "uri is null");
}

try {
    mediaPlayer.setDataSource(getApplicationContext(), uri);
    mediaPlayer.prepare();  
    mediaPlayer.setLooping(true);
    mediaPlayer.start();
} catch (Exception e) {
    // Handle exception
}

The uri is not null and the ringtone plays...

Can anyone explain what is going on here, and what I am supposed to do to avoid this hack?

Thanks


Solution

  • RingtoneManager has two constructors. One of them takes in a Context and the other takes an Activity. According to the docs, the one that takes an Activity will manage the cursor for you. The one that takes a Context will not.

    If the docs are to be believed, sounds like your this is not an Activity, and thus, the RingtoneManager instance you are getting is not managing the cursor and is expecting you to call getCursor().