2013-07-28 58 views
0

目前我正在使用Android音板,到目前爲止它沒有問題。我用圖像等做了一個漂亮的listView,但我無法正確加載聲音。 soundfiles的位置存儲在arraylist中,我試圖用getById()加載它們。MediaPlayer,onItemClickListener和NullPointerException。怎麼了?

這裏是我做了什麼

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
           int position, long id) { 




      mp = MediaPlayer.create(MainActivity.this, Uri.parse("android.resource://" + getPackageName() + "/" + 
        Model.GetbyId(position + 1).Sound)); 
      if(mp == null) { 
       Toast.makeText(getApplicationContext(), 
           "Mediaplayer is null. Link was: "+link , Toast.LENGTH_LONG) 
           .show(); 
      } else { 
       mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 

        @Override 
        public void onCompletion(MediaPlayer mediaplayer) { 
         mediaplayer.stop(); 
         mediaplayer.release(); 
        } 
       }); 
       mp.start(); 

      } 


     } 
    }); 

誰能告訴我,爲什麼它不工作?我仍然是初學者,經過數小時的努力和研究後,我無法想象它。

編輯:這是logcat中的錯誤。我敢肯定的文件是存在的......

07-28 12:56:53.998  124-593/? I/AwesomePlayer: setDataSource_l(URL suppressed) 
07-28 12:56:53.998  124-7235/? E/: Failed to open file  'R.raw.so_schoenasummervielheu'. (No such file or directory) 
07-28 12:56:53.998 6760-6771/? E/MediaPlayer: error (1, -2147483648) 
07-28 12:56:54.008 6760-6760/? D/MediaPlayer: create failed: 
    java.io.IOException: Prepare failed.: status=0x1 
    at android.media.MediaPlayer.prepare(Native Method) 
    at android.media.MediaPlayer.create(MediaPlayer.java:792) 
    at android.media.MediaPlayer.create(MediaPlayer.java:769) 
    at com.spruechmeischtr2000.android.MainActivity$1.onItemClick(MainActivity.java:45) 
    at android.widget.AdapterView.performItemClick(AdapterView.java:298) 
    at android.widget.AbsListView.performItemClick(AbsListView.java:1100) 
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788) 
    at android.widget.AbsListView$1.run(AbsListView.java:3463) 
    at android.os.Handler.handleCallback(Handler.java:730) 
    at android.os.Handler.dispatchMessage(Handler.java:92) 
    at android.os.Looper.loop(Looper.java:137) 
    at android.app.ActivityThread.main(ActivityThread.java:5103) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:525) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
    at dalvik.system.NativeStart.main(Native Method) 

編輯:只是想在這裏回答我的問題(StackOverflow上不會讓我的三個小時,這樣做)。其實代碼是好的,我做錯了一件事是我聲明我的聲音文件作爲字符串變量,而不是我的ArrayList/Itemadapter int資源ID。感謝所有試圖幫助我的人:)

+0

你可以發佈logcat嗎? – Shark

+0

對於聲卡應用程序,您可能也會考慮使用'SoundPool'而不是'MediaPlayer',它可能更合適:http://developer.android.com/reference/android/media/SoundPool.html –

+0

Sure , 1秒。 –

回答

0

不要忘記添加mediaplayer.prepare();