2012-03-02 61 views
0

我一直在一個簡單的應用按鈕點擊播放隨機聲字節和幾乎擁有一切工作正常,但由於某些原因,應用力click事件後隨機關閉,我不能找出是什麼導致了這個問題,因爲我對android編程還比較陌生。任何援助將不勝感激!onclick事件導致隨機FC

我的代碼:

public class Soundboard extends Activity { 
    private SoundManager mSoundManager; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // FULLSCREEN CODE 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
           WindowManager.LayoutParams.FLAG_FULLSCREEN); 

     setContentView(R.layout.main); 

     mSoundManager = new SoundManager(); 
     mSoundManager.initSounds(getBaseContext()); 
     mSoundManager.addSound(0, R.raw.sound1); 
     mSoundManager.addSound(1, R.raw.sound2); 
     mSoundManager.addSound(2, R.raw.sound3); 
     mSoundManager.addSound(3, R.raw.sound4); 
     mSoundManager.addSound(4, R.raw.sound5); 
     mSoundManager.addSound(5, R.raw.sound6); 
     mSoundManager.addSound(6, R.raw.sound7); 
     mSoundManager.addSound(7, R.raw.sound8); 
     mSoundManager.addSound(8, R.raw.sound9); 
     mSoundManager.addSound(9, R.raw.sound10); 

     ImageButton SoundButton1 = (ImageButton)findViewById(R.id.Btn_Push); 
     SoundButton1.setOnClickListener(new OnClickListener() { 

    public void onClick(View v) { 

     Random r = new Random(); 
     int x = r.nextInt(11); 
     mSoundManager.playSound(x); 

    } 
}); 
} 
} 

的logcat:

W/dalvikvm(1146): threadid=1: thread exiting with uncaught exception (group=0x40015560) 
E/AndroidRuntime(1146): FATAL EXCEPTION: main 
E/AndroidRuntime(1146): java.lang.NullPointerException 
E/AndroidRuntime(1146):  at com.tmapps.twss.SoundManager.playSound(SoundManager.java:37) 
E/AndroidRuntime(1146):  at com.tmapps.twss.Soundboard$1.onClick(Soundboard.java:49) 
E/AndroidRuntime(1146):  at android.view.View.performClick(View.java:2485) 
E/AndroidRuntime(1146):  at android.view.View$PerformClick.run(View.java:9080) 
E/AndroidRuntime(1146):  at android.os.Handler.handleCallback(Handler.java:587) 
E/AndroidRuntime(1146):  at android.os.Handler.dispatchMessage(Handler.java:92) 
E/AndroidRuntime(1146):  at android.os.Looper.loop(Looper.java:123) 
E/AndroidRuntime(1146):  at android.app.ActivityThread.main(ActivityThread.java:3683) 
E/AndroidRuntime(1146):  at java.lang.reflect.Method.invokeNative(Native Method) 
E/AndroidRuntime(1146):  at java.lang.reflect.Method.invoke(Method.java:507) 
E/AndroidRuntime(1146):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 
E/AndroidRuntime(1146):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 
E/AndroidRuntime(1146):  at dalvik.system.NativeStart.main(Native Method) 

回答

1

那麼,你必須:

r.nextInt(11) 

從0-10得到的隨機數,但你只有聲音的0-9。所以當你碰巧碰到10時,你會得到一個NullPointerException

+0

嗯,我想我誤解了#在(),這是有道理的,爲什麼它現在得到NullPointerException異常。 – n00bdev 2012-03-02 21:37:28