[英]Android NullPointerException when using setDataSource with a URI
大家好,我正在為Android制作音樂播放器,當我去選擇要播放的歌曲時,應用崩潰並產生錯誤:
09-16 13:10:08.671: I/System.out(22932): Reset worked
09-16 13:10:08.671: I/System.out(22932): com.example.taptwisttunes.Song@42d97240
09-16 13:10:08.671: I/System.out(22932): about to load song
09-16 13:10:08.671: I/System.out(22932): content://media/external/audio/media/23657
09-16 13:10:08.671: I/System.out(22932): content://media/external/audio/media/23657
09-16 13:10:08.671: D/AndroidRuntime(22932): Shutting down VM
09-16 13:10:08.671: W/dalvikvm(22932): threadid=1: thread exiting with uncaught exception (group=0x41fee700)
09-16 13:10:08.676: E/AndroidRuntime(22932): FATAL EXCEPTION: main
09-16 13:10:08.676: E/AndroidRuntime(22932): java.lang.IllegalStateException: Could not execute method of the activity
這是我的playSong方法,有人知道我在做什么錯嗎?
public void playSong(){ //this method plays the song by retrieving ID and modeling it as uri
//player.reset(); //resets media player
System.out.println("Reset worked");
Song playSong = songs.get(sPos); // retrieves song to be played
System.out.println(playSong);
long currSong = playSong.getId();
System.out.println("about to load song");
Uri trackUri = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong);
System.out.println(trackUri);
System.out.println(trackUri.toString());
//try block not sure if uri will work as a data source
try{
player.setDataSource(this.getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("Music Service", "There has been an error setting the data source", e);
}
player.prepareAsync();
}
MediaPlayer#prepareAsync
引發IllegalStateException
,您需要處理該異常或向您的方法聲明中添加引發,因此方法的調用者將處理該異常。 是你做的嗎? 就像是 :
try{
player.prepareAsync();
}
catch(IllegalStateException ise){
//do what you want when this exception is thrown
}
有了錯誤和給出的代碼,我相信您已經調用player
實例來播放一些歌曲,而您正在嘗試第二次播放歌曲。
另外,您已經注釋了player.reset().
確保您的player
實例為reset() , prepare()並設置為正確播放文件。
下圖來自android開發人員 ,應該可以幫助您更好地理解該概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.