在我的应用中,用户从ListView中进行选择,并根据位置播放歌曲。当用户试图选择一首歌时,Galaxy SII \ SIII手机正在抛出NullPointerExceptions。我将活动设置为保持纵向方向,并具有一个主要布局(activity_main.xml)。
崩溃报告:
java.lang.NullPointerException
at com.soundboard.MainActivity.playSong(MainActivity.java:466)
at com.soundboard.MainActivity$10.onItemClick(MainActivity.java:286)
at android.widget.AdapterView.performItemClick(AdapterView.java:301)
at android.widget.AbsListView.performItemClick(AbsListView.java:1519)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3278)
at android.widget.AbsListView$1.run(AbsListView.java:4327)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5293)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
代码:
public void playSong(int songIndex){
Log.d(TAG, "Starting playSong(" + songIndex + ")");
FlurryAgent.logEvent("Starting playSong("+songIndex+")");
try {
if(mp != null){
mp.release();
}
try{
mp = MediaPlayer.create(MainActivity.this, songManager.getSong(songIndex).getResId());
} catch(Exception e){
FlurryAgent.logEvent("playSong():mediaPlayer.create");
}
try{
mp.prepare();
} catch(Exception e){
Log.e(TAG, "Caught error preparing: "+e.getMessage());
FlurryAgent.logEvent("playSong():mediaPlayer.prepare");
e.printStackTrace();
}
mp.start();//ERROR IS ON THIS LINE
FlurryAgent.logEvent("mp.start()");
// Displaying Song title
String songTitle = songManager.getSong(songIndex).getName();
songTitleLabel.setText(songTitle);
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
Log.e(TAG, "Caught IllegalArgumentException: "+e.getMessage());
} catch (IllegalStateException e) {
Log.e(TAG, "Caught IllegalStateException: "+e.getMessage());
}
}
@Override
public void onPause(){
super.onPause();
if(mp != null){
try{
mp.stop();
mp.release();
} catch(Exception e){
Log.e(TAG, "Error in onPause()\n ");
}
}
mHandler.removeCallbacks(mUpdateTimeTask);
songProgressBar.setProgress(0);
}
答案 0 :(得分:1)
如果MediaPlayer.create失败,则mp可以为null。然后你会在它上面调用mp.prepare,这会崩溃。如果创建失败,您希望从此功能返回,而不是继续尝试播放歌曲。