How to add recently played song in listview?
<p>I am new to android development and currently I'm implementing simple music player app in android.So, Here my question is that I am using fragment in this music player and I want add recently played song in another listview fragment.</p>

<p>This is my main player fragment class.......</p>

<pre><code>private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
private MediaPlayer mp;
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;
private AudioManager audioManager = null;
SongAdapter songAdapter;

public Player(int position) {
    songIndex = position;

}

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

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

                        super.onCreate(savedInstanceState);

    // 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.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);


    //get bundle data
    /*Bundle b = getArguments();
    int position = b.getInt("songIndex");
    Log.i("position...","...."+position);*/

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

    //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();

    // Mediaplayer

    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;

}

private void initAudio() {
    getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    mp = MediaPlayer.create(getActivity(),R.raw.test);
    mp.setLooping(true);
    setupVisualizerFxAndUI();
    mVisualizer.setEnabled(true);
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mVisualizer.setEnabled(false);
        }
    });
    mp.start();
}

private void setupVisualizerFxAndUI() {
    mVisualizer = new Visualizer(mp.getAudioSessionId());
    mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
    mVisualizer.setDataCaptureListener(
            new Visualizer.OnDataCaptureListener() {
                public void onWaveFormDataCapture(Visualizer visualizer,
                                                  byte[] bytes, int samplingRate) {
                    mVisualizerView.updateVisualizer(bytes);
                }

                public void onFftDataCapture(Visualizer visualizer,
                                             byte[] bytes, int samplingRate) {
                }
            }, Visualizer.getMaxCaptureRate() / 2, true, false);
}

@Override
public void onActivityResult(int requestCode,
                             int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == 100){
        currentSongIndex = data.getExtras().getInt("songIndex");
        // play selected song
        playSong(currentSongIndex);
    }

}
public void playSong(int songIndex){
    try {
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).getSongPath());
        mp.prepare();
        mp.start();
        String songTitle = songsList.get(songIndex).getSongTitle();
        songTitleLabel.setText(songTitle);

        btnPlay.setImageResource(R.drawable.btn_pause);
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);
        updateProgressBar();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask,100);
}
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);
    }
};

@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 onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mUpdateTimeTask);
    if (mp != null) {
        if (mp.isPlaying()) mp.stop();
        mp.reset();
        mp.release();
    }
}
public void onBackPressed() {

    new AlertDialog.Builder(getActivity())
            .setIcon(R.drawable.musiclogo)
            .setTitle("Closing M-Player")
            .setMessage("Are you sure you want to close this application?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {

                public void onClick(DialogInterface dialog, int which) {
                    getActivity().finish();
                }

            })
            .setNegativeButton("No",null)
            .show();
}}
</code></pre>

<p>This is my playlist(Songlist) fragment and extend listfragment</p>

<pre><code>EditText edtSearch;
ListAdapter adapter;
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);

    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);
    }
    // Adding menuItems to ListView
   /* adapter = new SimpleAdapter(getActivity(), songsListData, R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
            R.id.songTitle });*/

    songAdapter = new SongAdapter(getActivity(),songsList);
    setListAdapter(songAdapter);
    // selecting single ListView item
    final 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) {

            // getting listitem index
            Log.i("Index", "..." + position);
            // Starting new intent
            Intent i = new Intent(getActivity().getApplicationContext(),Main.class);
            SongModel songModel = (SongModel) songAdapter.getItem(position);
            int indexOfSong = songAdapter.songsList.indexOf(songModel);
            // Sending songIndex to PlayerActivity
            i.putExtra("songIndex", indexOfSong);
            getActivity().setResult(100, i);
            startActivityForResult(i, 100);

        }
    });
    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);
        }
    });
}
</code></pre>

<p>This is my songmanager class.</p>

<pre><code>public ArrayList&lt;SongModel&gt; songList = new ArrayList&lt;SongModel&gt;();
// SDCard Path
final String MEDIA_PATH = new String("/sdcard/");

// Constructor
public SongsManager(){

}


public ArrayList&lt;SongModel&gt; getPlayList(){
    File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length &gt; 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            SongModel setter = new SongModel();
            setter.setSongPath(file.getPath());
            setter.setSongTitle(file.getName().substring(0, (file.getName().length() - 4)));

            songList.add(setter);
        }
    }
    return songList;
}
class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}
</code></pre>

<p>This my song adapter and extend base adapter.</p>

<pre><code>Context context;
//private ArrayList&lt;SongModel&gt; songsList = null;
SongAdapter songAdapter;
private ArrayList&lt;SongModel&gt; songsListDat = null;
public ArrayList&lt;SongModel&gt; songsList;
private static LayoutInflater inflater;

public SongAdapter(FragmentActivity activity, ArrayList&lt;SongModel&gt; songsListDat) {

    this.context = activity;
    this.songsListDat = songsListDat;
    this.songsList = new ArrayList&lt;SongModel&gt;();
    this.songsList.addAll(songsListDat);

}

@Override
public int getViewTypeCount() {

    return getCount();
}

@Override
public int getCount() {
    return songsListDat.size();
}

@Override
public Object getItem(int position) {
    return songsListDat.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemViewType(int position) {

    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.playlist_item, null);

    TextView title = (TextView) vi.findViewById(R.id.songTitle); // title
    SongModel song = new SongModel();
    song = songsListDat.get(position);
    // Setting all values in listview
    title.setText(song.getSongTitle());

    return vi;
</code></pre>

<p>If anyone know the the logic of this please help me.
Thanks in advance</p>