Media Player for android中暂停方法的空指针异常

时间:2012-10-12 01:12:23

标签: android nullpointerexception media-player onclicklistener null-pointer

我一直在为MediaPlayer的方法获取空指针异常。我终于能够通过将播放代码和播放函数初始化为单独的方法并从onClick监听器内部调用该方法来使播放功能工作。

然而,我仍然得到应用暂停功能的空指针异常。我正在使用媒体播放器的暂停方法。如何让停顿工作?我认为问题出在我的代码结构中以及它是如何组织的。

我尝试将媒体播放器的初始化移动到代码中的其他位置。并且似乎没有任何工作。有什么想法吗?

// 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

1 个答案:

答案 0 :(得分:0)

您必须制作MediaPlayer播放器全局变量。对于pauseSong()方法,播放器不可见,因此您具有nullPointerException。在主类中创建一个MediaPlayer播放器,然后在onPlaySong()中初始化它,如下所示:

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