I am trying to do video streaming that is working fine in portrait mode. Then I added code for onConfigurationChange
to inflate another layout for landscape mode. but my app is getting crashed at this line:
int timeElapsed = mediaPlayer.getCurrentPosition();
Here I am getting mediaPlayer
as null while it has been already initialized.
MediaPlayer mediaPlayer; public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detailvideo); context = this; mediaPlayer = new MediaPlayer(); videoView = (VideoViewCustom) findViewById(R.id.videoplayer); try { videoView.setDimensions(1000, 200); videoView.getHolder().setFixedSize(1000, 200); videoView.setVideoPath(streamURL); videoView.setMediaController(mediaController); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // Close the progress bar and play the video public void onPrepared(MediaPlayer mp) { Log.d(TAG,"setOnPreparedListener"); mediaPlayer = mp; int timeDuration = 0; boolean videoPlaying = false; if(savedInstanceState != null) { timeDuration = savedInstanceState.getInt("timeduration"); videoPlaying = savedInstanceState.getBoolean("videoPlaying"); Log.d(TAG, "timeDuration saved:" + timeDuration); Log.d(TAG, "videoPlaying saved:" + videoPlaying); if (videoPlaying) { mediaPlayer.seekTo(timeDuration); mediaPlayer.start(); } else { mediaPlayer.seekTo(timeDuration); } } else { mediaPlayer.start(); } videoView.start(); finalTime = mediaPlayer.getDuration(); Log.d(TAG, "mp.getCurrentPosition():" + mediaPlayer.getCurrentPosition()); videoSeekBar.setProgress(timeDuration); videoSeekBar.setMax(finalTime); durationHandler.postDelayed(updateSeekBarTime,1000); } }); Runnable updateSeekBarTime = new Runnable() { public void run() { //get current position int timeElapsed = mediaPlayer.getCurrentPosition(); //**is crashing here after orientation change** //set seekbar progress videoSeekBar.setProgress((int) timeElapsed); Log.d(TAG,"timeElapsed:"+timeElapsed); //repeat yourself that again in 100 miliseconds durationHandler.postDelayed(this,1000); } };
How can I avoid this issue? And how can I start video again in landscape from the same position where user stopped in portrait mode? Thanks.