Why I'm getting this error "java.lang.IllegalStateException" in Mediaplayer android app
<p>I am new to android development and currently I am developing android mediaplayer simple application. So,my question is that why I am getting this exception.According to my project I have define three fragment, First fragment is Player fragment which is display the mediaplayer control and playing song, Second fragment is Playlist which is contain songlist, And third fragment is Recent playlist which is contain recently played song.In this project when I am clicking on playlist fragment item to play new song and suddenly generate <code>java.lang.IllegalStateException</code> this exception.</p>

<p>Here this is my player Fragment</p>

<pre><code>package com.v1.sensoft.m_player.Fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.Visualizer;
import android.net.sip.SipSession; 
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.MotionEventCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.v1.sensoft.m_player.Activity.AudioFxActivit;
import com.v1.sensoft.m_player.Adapter.SongAdapter;
import com.v1.sensoft.m_player.R;
import com.v1.sensoft.m_player.Utility.SongsManager;
import com.v1.sensoft.m_player.Utility.Utilities;
import com.v1.sensoft.m_player.Visualizer.SliderView;
import com.v1.sensoft.m_player.Visualizer.VisualizerView;
import com.v1.sensoft.m_player.djView.ClickWheel;
import com.v1.sensoft.m_player.djView.WheelModel;
import com.v1.sensoft.m_player.model.SongModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;


public class Player extends Fragment implements WheelModel.Listener,MediaPlayer.OnCompletionListener,SeekBar.OnSeekBarChangeListener {

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
public static MediaPlayer mp,mp2;
VisualizerView mVisualizerView;
SliderView sl;
private Visualizer mVisualizer;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList&lt;SongModel&gt; songsList = new ArrayList&lt;SongModel&gt;();
int songIndex;
SongAdapter songAdapter;
public Player(int position) {
    songIndex = position;
}

public Player() {

}


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    View android = inflater.inflate(R.layout.player, container, false);

    ClickWheel wheel = (ClickWheel) android.findViewById(R.id.wheel);
        wheel.getModel().addListener(this);
    // variable initialization for button
    btnPlay = (ImageButton) android.findViewById(R.id.btnPlay);
    btnForward = (ImageButton) android.findViewById(R.id.btnForward);
    btnBackward = (ImageButton) android.findViewById(R.id.btnBackward);
    btnNext = (ImageButton) android.findViewById(R.id.btnNext);
    btnPrevious = (ImageButton) android.findViewById(R.id.btnPrevious);
    btnRepeat = (ImageButton) android.findViewById(R.id.btnRepeat);
    btnShuffle = (ImageButton) android.findViewById(R.id.btnShuffle);
    songProgressBar = (SeekBar) android.findViewById(R.id.songProgressBar);
    songTitleLabel = (TextView) android.findViewById(R.id.songTitle);
        songTitleLabel.setSelected(true);
        songTitleLabel.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        songTitleLabel.setSingleLine(true);
    songCurrentDurationLabel = (TextView)android.findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView) android.findViewById(R.id.songTotalDurationLabel);
   // mVisualizerView = (VisualizerView) android.findViewById(R.id.myvisualizerview);
    //audioManager = (AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);

   /* //sliding finger up and increase and decrease volume
    android.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            int action = MotionEventCompat.getActionMasked(event);
            if (action == MotionEvent.ACTION_MOVE) {
                // put your volume change logic here, for example compare previously recorded x/y position to new one and change volume
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 5, 0);
            }
            return true;
        }
    });*/
    //Visualizer method
    mp = new MediaPlayer();
   // initAudio();

    songManager = new SongsManager();
    utils = new Utilities();

    // Listeners
    songProgressBar.setOnSeekBarChangeListener(this); // Important
    mp.setOnCompletionListener(this); // Important

    // Getting all songs list
    songsList = songManager.getPlayList();
    // By default play first song
    if (songIndex==0)
    {
        playSong(0);
    }
    else
    {
        playSong(songIndex);
    }
    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check for already playing
            if (mp.isPlaying()) {
                if (mp != null) {
                    mp.pause();
                    btnPlay.setImageResource(R.drawable.btn_play);
                }
            } else {
                // Resume song
                if (mp != null) {
                    mp.start();
                    btnPlay.setImageResource(R.drawable.btn_pause);
                }
            }

        }
    });
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int currentPosition = mp.getCurrentPosition();
            if(currentPosition + seekForwardTime &lt;= mp.getDuration()){
                mp.seekTo(currentPosition + seekForwardTime);
            }else{
                mp.seekTo(mp.getDuration());
            }
        }
    });
    btnBackward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int currentPosition = mp.getCurrentPosition();
            if(currentPosition - seekBackwardTime &gt;= 0){
                mp.seekTo(currentPosition - seekBackwardTime);
            }else{
                mp.seekTo(0);
            }

        }
    });
    btnNext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex &lt; (songsList.size() - 1)){
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            }else{
                playSong(0);
                currentSongIndex = 0;
            }

        }
    });
    btnPrevious.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex &gt; 0){
                playSong(currentSongIndex - 1);
                currentSongIndex = currentSongIndex - 1;
            }else{
                playSong(songsList.size() - 1);
                currentSongIndex = songsList.size() - 1;
            }

        }
    });
    btnRepeat.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isRepeat){
                isRepeat = false;
                Toast.makeText(getActivity().getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }else{
                isRepeat = true;
                Toast.makeText(getActivity().getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
                isShuffle = false;
                btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }
        }
    });
    btnShuffle.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isShuffle){
                isShuffle = false;
                Toast.makeText(getActivity().getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }else{
                isShuffle= true;
                Toast.makeText(getActivity().getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                isRepeat = false;
                btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }
        }
    });
    return android;

}
public void playSong(int songIndex){
    try {
        Log.e("playSong()...", "....is called");
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).getSongPath());
        mp.prepare();
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);
        String songTitle = songsList.get(songIndex).getSongTitle();
        songTitleLabel.setText(songTitle);
        btnPlay.setImageResource(R.drawable.btn_pause);
        updateProgressBar();
        mp.start();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Log.i("song...songIndex...", "..." + songIndex);

    mHandler.removeCallbacks(mUpdateTimeTask);
    if(resultCode == 100){
        currentSongIndex = data.getExtras().getInt("songIndex");
        Log.i("song...currentSongIndex...", "..." + currentSongIndex);
        // play selected song
        playSong(currentSongIndex);
    }

}
private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        long totalDuration = mp.getDuration();
        long currentDuration = mp.getCurrentPosition();

        songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));

        songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

        int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));

        songProgressBar.setProgress(progress);

        mHandler.postDelayed(this,100);
    }
};
private void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask,100);
}
@Override
public void onCompletion(MediaPlayer mp) {
    if(isRepeat){
        playSong(currentSongIndex);
    } else if(isShuffle){
        Random rand = new Random();
        currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
        playSong(currentSongIndex);
    } else{
        if(currentSongIndex &lt; (songsList.size() - 1)){
            playSong(currentSongIndex + 1);
            currentSongIndex = currentSongIndex + 1;
        }else{
            playSong(0);
            currentSongIndex = 0;
        }
    }
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    mp.seekTo(currentPosition);
    updateProgressBar();
}
@Override
public void onDialPositionChanged(WheelModel sender, int nicksChanged) {

    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    mp2 =MediaPlayer.create(getActivity(),R.raw.djlazer);
    mp2.start();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (this.isVisible()) {

        if (!isVisibleToUser) {

        }
    }
}
@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mUpdateTimeTask);
    if(mp!=null)
    {
        if(mp.isPlaying()) mp.stop();
        mp.reset();
        mp.release();
    }
}
}
</code></pre>

<p>Playlist fragment.</p>

<pre><code>public class Playlists extends ListFragment {


EditText edtSearch;
SongAdapter songAdapter;
ArrayList&lt;SongModel&gt; songList = new ArrayList&lt;SongModel&gt;();
SongsManager songsManager = new SongsManager();

// Songs list
public ArrayList&lt;SongModel&gt; songsList = new ArrayList&lt;&gt;();
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
     View windows = inflater.inflate(R.layout.playlist, container, false);
     return windows;
}

@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
    super.onViewCreated(v, savedInstanceState);

    getListView().setFastScrollEnabled(true);
    //ListView animation
    LayoutAnimationController controller
            = AnimationUtils.loadLayoutAnimation(
            getActivity(), R.anim.list_layout_controller);
    getListView().setLayoutAnimation(controller);
    edtSearch = (EditText)getView().findViewById(R.id.search);
    final ArrayList&lt;SongModel&gt; songsListData = songsManager.songList;
    Log.i("songsListData...",""+songsListData.size());
    SongsManager plm = new SongsManager();

    // get all songs from sdcard
    this.songsList = plm.getPlayList();
    // looping through playlist
    for (int i = 0; i &lt; songsListData.size(); i++) {
        // creating new HashMap
        SongModel song = songsListData.get(i);
        // adding HashList to ArrayList
        songsListData.add(song);
    }

    songAdapter = new SongAdapter(getActivity(),songsList);
    setListAdapter(songAdapter);
    // selecting single ListView item
    ListView lv = getListView();

    // listening to single listitem click
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView&lt;?&gt; parent, View arg0,
                                int position, long id) {

            Log.i("Index", "..." + position);
            songAdapter.setSelectedIndex(position);
            Intent i = new Intent(getActivity().getApplicationContext(),Main.class);
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
            SongModel songModel = (SongModel) songAdapter.getItem(position);
            int indexOfSong = songAdapter.songsList.indexOf(songModel);

            // Sending songIndex to PlayerActivity
            i.putExtra("songIndex", indexOfSong);

            startActivityForResult(i, 100);


            //putting song in recentSongList arraylist
            SongModel model = (SongModel) songAdapter.getItem(position);
            model.setSongTitle(songModel.getSongTitle());
            model.setSongPath(songModel.getSongPath());
            Constant.recentSongList.add(model);
            Log.i("recentSongList...","..."+Constant.recentSongList.size());
            getActivity().finish();
        }
    });
    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {

            removeItemFromList(position);
            return true;
        }

        private void removeItemFromList(int position) {

            final int deletePosition = position;

            AlertDialog.Builder alert = new AlertDialog.Builder(
                    getActivity());

            alert.setTitle("Delete");
            alert.setMessage("Do you want delete this song?");
            alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TOD O Auto-generated method stub

                    // main code on after clicking yes
                    songsList.remove(deletePosition);
                    songAdapter.notifyDataSetChanged();
                    songAdapter.notifyDataSetInvalidated();

                }
            });
            alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });

            alert.show();
        }
    });
    edtSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String text = edtSearch.getText().toString().toLowerCase(Locale.getDefault());
            songAdapter.filter(text);
        }
    });
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (this.isVisible()) {
        // If we are becoming invisible, then...
        Log.d("setUserVisibleHint()...", "PlayList...Visible");
        if (!isVisibleToUser) {
            Log.d("setUserVisibleHint()...", "PlayList...notVisible");
            // TODO stop audio playback
        }
    }
}
</code></pre>

<p>And this is my logcat</p>

<pre><code>09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:    FATAL EXCEPTION: main
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:  Process: com.v1.sensoft.m_player, PID: 17474
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime: java.lang.IllegalStateException
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:      at android.media.MediaPlayer.getDuration(Native Method)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at com.v1.sensoft.m_player.Fragment.Player$8.run(Player.java:289)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:808)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:103)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:193)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5333)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
09-14 18:43:12.052 17474-17474/com.v1.sensoft.m_player E/AndroidRuntime:       atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
</code></pre>

<p>So,How I can solve this problem.If any know what is the problem please help.
Thank in advance...</p>