[Java for Android App Development] AmatuerAppDeveloper:
Right I've been doing some changes on my media player app but I've ran into a bit of a problem.

So here's the question:

Before i started the changes i had one ImageButton on the music player which returned a list of all the songs listed on the phone and i have an onItemClick method which once clicked, would play the selected song BUT i didn't want it to just be a list of songs, i want to categorize them into two buttons. A "Albums" button and an "All songs" button so i managed to do the all songs button perfectly, UNTIL you go to click and play the song, once the songs clicked it'll go back to the player but won't automatically play the song like it did before...

And at the moment you can only listen to songs buy clicking "Play" rather than choosing manually.

So i need to know how i go about making the selected song play through the "All songs" button

Here's what i have so far on the MainActivity:

public class MainActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnSongList;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private ImageButton eq;
// Media Player
private MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private MusicButtons MusicButtons;
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<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);

// All player buttons

btnPlay = (ImageButton) findViewById(R.id.btnPlay);
btnForward = (ImageButton) findViewById(R.id.btnForward);
btnBackward = (ImageButton) findViewById(R.id.btnBackward);
btnNext = (ImageButton) findViewById(R.id.btnNext);
btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
btnSongList = (ImageButton) findViewById(R.id.btnSongList);
btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTitleLabel = (TextView) findViewById(R.id.songTitle);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
eq = (ImageButton) findViewById(R.id.eq);

// Mediaplayer
mp = new MediaPlayer();
songManager = new SongsManager();
setMusicButtons(new MusicButtons());

utils = new Utilities();

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

// Getting all songs list
songsList = songManager.getPlayList(this);

/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
btnPlay.setOnClickListener(new View.OnClickListener() {

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

}
});

/**
* Forward button click event
* Forwards song specified seconds
* */
btnForward.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekForward time is lesser than song duration
if(currentPosition + seekForwardTime <= mp.getDuration()){
// forward song
mp.seekTo(currentPosition + seekForwardTime);
}else{
// forward to end position
mp.seekTo(mp.getDuration());
}
}
});

/**
* Backward button click event
* Backward song to specified seconds
* */
btnBackward.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekBackward time is greater than 0 sec
if(currentPosition - seekBackwardTime >= 0){
// forward song
mp.seekTo(currentPosition - seekBackwardTime);
}else{
// backward to starting position
mp.seekTo(0);
}

}
});

/**
* Next button click event
* Plays next song by taking currentSongIndex + 1
* */
btnNext.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// check if next song is there or not
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 5);
currentSongIndex = currentSongIndex + 5;
}else{
// play first song
playSong(0);
currentSongIndex = 0;
}

}
});

/**
* Back button click event
* Plays previous song by currentSongIndex - 1
* */
btnPrevious.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
if(currentSongIndex > 0){
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
}else{
// play last song
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() - 1;
}

}
});

/**
* Button Click event for Repeat button
* Enables repeat flag to true
* */
btnRepeat.setOnClickListener(new View.OnClickListener() {

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

/**
* Button Click event for Shuffle button
* Enables shuffle flag to true
* */
btnShuffle.setOnClickListener(new View.OnClickListener() {

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

/**
*
* HERE'S THE "ALL SONGS" BUTTON!
* */
btnSongList.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), MusicButtons.class);
startActivityForResult(i, 99);
return;
}
});

eq.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), EQ.class);
startActivityForResult(i, 100);
}
});

}

/**
* Receiving song index from playlist view
* and play the song
*
* HERE'S THE LIST OF SONGS
* */
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 100){
currentSongIndex = data.getExtras().getInt("songPath");
// play selected song
playSong(currentSongIndex);
}

}

/**
* Function to play a song
* @param songIndex - index of song
*
* AND OF COURSE, HERE'S WHAT IS SUPPOSED TO PLAY THE SONG!!
* */
public void playSong(int songIndex){
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);

// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);

// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);

// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Update timer on seekbar
* */
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}

/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();

// Displaying Total Duration time
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);

// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
private boolean doubleBackToExitPressedOnce;

/**
*
* */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
* When user starts moving the progress handler
* */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
* When user stops moving the progress hanlder
* */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

// forward or backward to certain seconds
mp.seekTo(currentPosition);

// update timer progress again
updateProgressBar();
}

/**
* On Song Playing completed
* if repeat is ON play same song again
* if shuffle is ON play random song
* */
@Override
public void onCompletion(MediaPlayer arg0) {

// check for repeat is ON or OFF
if(isRepeat){
// repeat is on play same song again
playSong(currentSongIndex);
} else if(isShuffle){
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else{
// no repeat or shuffle ON - play next song
if(currentSongIndex < (songsList.size() - 1)){
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
}else{
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}

@Override
public void onDestroy(){
super.onDestroy();
mHandler.removeCallbacks(mUpdateTimeTask);
mp.release();
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please Double Tap To Exit!", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {

@Override
public void run() {
doubleBackToExitPressedOnce=false;

}
}, 2000);
}

public MusicButtons getMusicButtons() {
return MusicButtons;
}

public void setMusicButtons(MusicButtons musicButtons) {
MusicButtons = musicButtons;
}
}

And here's the class file for the "All songs" button (I'm yet to add the "Albums" button):

public class MusicButtons extends Activity{
private Button allsongs;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist_buttons);

allsongs = (Button) findViewById(R.id.allsongsButton);

allsongs.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
startActivityForResult(i, 99);
finish();
}
});

}
}

And FINALLY my MediaStore code

public class SongsManager {

public SongsManager() {

}
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

public ArrayList<HashMap<String, String>> getPlayList(Context c) {

/*use content provider to get beginning of database query that queries for all audio by display name, path
and mimtype which i dont use but got it incase you want to scan for mp3 files only you can compare with RFC mimetype for mp3's
*/
final Cursor mCursor = c.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.MIME_TYPE }, null, null,
"UPPER(" + MediaStore.Audio.Media.TITLE + ") ASC");

String songTitle = "";
String songPath = "";

/* run through all the columns we got back and save the data we need into the arraylist for our listview*/
if (mCursor.moveToFirst()) {
do {

mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.MIME_TYPE));

songTitle = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
songPath = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
HashMap<String, String> song = new HashMap<String, String>();

song.put("songTitle", songTitle);
song.put("songPath", songPath);

songsList.add(song);

} while (mCursor.moveToNext());
}

mCursor.close(); //cursor has been consumed so close it
return songsList;
}

public ArrayList<HashMap<String, String>> getPlayList() {
// TODO Auto-generated method stub
return null;
}

}

Sorry for all the code!!

I hope I've managed to explain my question properly so that you can understand it

Cheers

Ryan