前几天我在开发者控制台中弹出了这个错误,我不明白这个问题。
我正在尝试播放位于我项目原始文件夹中的mp3
文件。
MediaPlayer player = new MediaPlayer();
try {
player.setAudioStreamType(AudioManager.STREAM_RING);
Uri uri = Uri.parse(pref.getString(Preferences.CONN_TONE,""));
if(uri != null){
player.setDataSource(this, uri);
}else{
player = MediaPlayer.create(this, R.raw.default_tone); //error here
}
player.prepare();
}
在这一行player = MediaPlayer.create(this, R.raw.default_tone);
它给我一个错误说StringIndexOutOfBoundsException
当我给它一个int资源播放一个mp3文件时,为什么它会抛出一个字符串异常?另外,为什么这会给这个用户带来错误。
堆栈跟踪
java.lang.RuntimeException: Unable to start activity ComponentInfo{ecm2.android/ecm2.android.Dialogs.MessageBox}: java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=7
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2351)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5454)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=7
at java.lang.String.startEndAndLength(String.java:593)
at java.lang.String.substring(String.java:1474)
at android.media.MediaPlayer.isStreaming(MediaPlayer.java:3847)
at android.media.MediaPlayer.isNeedAddProxyInfo(MediaPlayer.java:3856)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1103)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1031)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1002)
at ecm2.android.Dialogs.MessageBox.playTone(MessageBox.java:75)
at ecm2.android.Dialogs.MessageBox.onCreate(MessageBox.java:43)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
答案 0 :(得分:1)
确保已设置Preferences.CONN_TONE
,或者默认值指向应用具有的默认mp3文件。最好的猜测是,通过将“”传递给Uri.parse()
来创建一个无效的Uri,这会在使用可能是无效的Uri调用MediaPlayer.create()
时导致异常。