NullPoinetrExceotion getApplicationContext

时间:2018-07-14 12:05:03

标签: android service nullpointerexception

我正在尝试开发音乐播放器,但在从服务调用方法(skipToNext)时遇到问题... 我正在尝试从PlayerActivity中的服务调用skipToNext函数(单击前进的图像按钮),但是发生nullPointer异常。

PlayerActivity:

public class PlayerActivity extends AppCompatActivity {
private   MediaPlayerService service = new MediaPlayerService();
private SeekBar seekBar;
private TextView currentDurationTextView;
MusicFragment fragment = new MusicFragment();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_player);
    setupViews();
}

private void setupViews() {
    //Setup Play Button
    final ImageView playImageView = findViewById(R.id.iv_play);
    if (MediaPlayerService.mediaPlayer.isPlaying()) {
        playImageView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_stat_pause, null));
    }
    playImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (MediaPlayerService.mediaPlayer.isPlaying()) {
                service.pauseMedia();
                playImageView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_stat_play, null));
            } else if (!MediaPlayerService.mediaPlayer.isPlaying()) {

                service.resumeMedia();
                playImageView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_stat_pause, null));

            }
        }
    });
    //Setup Forward Button
    ImageView forwardImageView = findViewById(R.id.iv_forward);
    forwardImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

           service.skipToNext();


        }
    });
    // Setup Rewind Button
    ImageView rewindImageView = findViewById(R.id.iv_rewind);
    rewindImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          service.skipToPrevious();
        }
    });

    //setup title TextView
    TextView titleTextView = findViewById(R.id.txt_song_title);
    titleTextView.setText(HomeActivity.getInstance().titleAudioList.get(fragment.audioIndex).getTitle());

    //Setup Duration TextView
    TextView totalDurationTextView = findViewById(R.id.txt_total_time);
    totalDurationTextView.setText(formatDuration(MediaPlayerService.mediaPlayer.getDuration()));
    currentDurationTextView = findViewById(R.id.txt_current_time);


    // Setup SeekBar
    seekBar = findViewById(R.id.seek_bar);
    seekBar.setMax(MediaPlayerService.mediaPlayer.getDuration());
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                MediaPlayerService.mediaPlayer.seekTo(progress);
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    Timer timer = new Timer();
    timer.schedule(new MainTimer(), 0, 1000);
}


private String formatDuration(long duration) {
    int second = (int) duration / 1000;
    int minute = second / 60;
    second %= 60;
    return String.format(Locale.ENGLISH, "%02d", minute) + ":" + String.format(Locale.ENGLISH, "%02d", second);

}

private class MainTimer extends TimerTask {

    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                seekBar.setProgress(MediaPlayerService.mediaPlayer.getCurrentPosition());
                currentDurationTextView.setText(formatDuration(MediaPlayerService.mediaPlayer.getCurrentPosition()));
            }
        });

    }
}

}

和我的服务:

 public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
    MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,  MediaPlayer.OnInfoListener
    , AudioManager.OnAudioFocusChangeListener {
       public void skipToNext() {

    if (audioIndex == audioList.size() - 1) {
        audioIndex = 0;
        activeAudio = audioList.get(audioIndex);
    } else {
        activeAudio = audioList.get(++audioIndex);
    }
    new StorageUtil(getApplicationContext()).storeAudioIndex(audioIndex);
    stopMedia();
    mediaPlayer.reset();
    initMediaPlayer();
}

}

com.example.developer.musicplayer E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.developer.musicplayer, PID: 7461
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                                 at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
                                                                                 at com.example.developer.musicplayer.Service.MediaPlayerService.skipToNext(MediaPlayerService.java:293)
                                                                                 at com.example.developer.musicplayer.Activity.PlayerActivity$2.onClick(PlayerActivity.java:61)
                                                                                 at android.view.View.performClick(View.java:5198)
                                                                                 at android.view.View$PerformClick.run(View.java:21147)
                                                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                 at android.os.Looper.loop(Looper.java:148)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 个答案:

答案 0 :(得分:0)

这不是您使用Service的方式。要么:

  • 摆脱extends Service并在MediaPlayerService中修复其余代码,或者

  • 正确地使用Service,而不是自己创建一个实例(不要创建new MediaPlayerService()),而是使用startService()或也许使用bindService()

    < / li>

您当前的代码为您提供了MediaPlayerService且未正确初始化。结果,您从Service继承的方法(例如getApplicationContext())将不起作用。

The documentation介绍了如何使用Service。 Android应用程序开发方面的书籍也是如此-free older editions中的one of my books包含了大量有关使用服务的资料。

答案 1 :(得分:0)

尝试这样:

new StorageUtil(this).storeAudioIndex(audioIndex);