0

我不斷收到MediaPlayer方法的空指針異常。我終於可以通過將播放和初始化播放函數的代碼移動到單獨的方法中並從onClick監聽器中調用該方法來使播放函數起作用。在Mediaplayer中爲暫停方法的空指針異常android

但是,我仍然得到應用程序暫停功能的空指針異常。我正在使用媒體播放器的暫停方法。如何獲得暫停工作?我認爲問題出在我的代碼結構中,以及它是如何組織的。

我試着將媒體播放器的初始化移動到代碼中的不同位置。而且似乎沒有任何工作。有任何想法嗎?

// onclick listener for the playing the selected song 
playB.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) { 
     playSong(); 
    } 
}); 

// onclick listener for pausing the song that is playing 
pauseB.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) { 
     pauseSong(); 
    } 
}); 

// method to pause song 
public void pauseSong(){ 
    player.pause(); 
    length = player.getCurrentPosition(); 
} 

// method to play song and initialize the MediaPlayer class with one file 
// from the drawable folder, need to initialize with something or it will be null 
// for that i decided to use an mp3 in R.raw folder 
public void playSong(){ 
    // Play song 
    MediaPlayer player = MediaPlayer.create(this, R.raw.g2); 
    player.reset(); 
    try { 
     player.setDataSource(selectedAudioPath); 

     player.prepare(); 
    } catch (IllegalArgumentException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IllegalStateException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    player.seekTo(length); 
    player.start(); 
} // play method 

回答

0

您必須製作一個MediaPlayer播放器全局變量。播放器對於pauseSong()方法不可見,因此您有nullPointerException。在你的主類創建一個MediaPlayer播放器,然後在onPlaySong()初始化它只是這樣的:

player = MediaPlayer.create(this, R.raw.g2); 
+0

這是問題之一,謝謝 – Kevik