在我的应用程序中,用户从 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);
}