0

I have been trying to implement next song button in my audio player app. I copied some code from a tutorial but its not working.The button for next song is btnNext and the method is cde(), its the last method in the code. The button gets clicked but next song is not played, current song keeps playing.How do I fix this ?

package com.example.dell_1.myapp3;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.R.attr.path;

public class PlayListActivity extends Activity {

    private String[] mAudioPath;
    private MediaPlayer mMediaPlayer;
    private String[] mMusicList;
    int currentPosition = 0;
    private List<String> songs = new ArrayList<>();

    MediaMetadataRetriever metaRetriver;
    byte[] art;
    ImageView album_art;
    TextView album;
    TextView artist;

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

        mMediaPlayer = new MediaPlayer();
        ListView mListView = (ListView) findViewById(R.id.list);

        mMusicList = getAudioList();

        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, mMusicList);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                    long arg3) {

                try {
                    playSong(mAudioPath[arg2]);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private String[] getAudioList() {
        final Cursor mCursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
                "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");

        int count = mCursor.getCount();

        String[] songs = new String[count];
        mAudioPath = new String[count];
        int i = 0;
        if (mCursor.moveToFirst()) {
            do {
                songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                i++;
            } while (mCursor.moveToNext());
        }

        mCursor.close();

        return songs;
    }


    private void playSong(String path) throws IllegalArgumentException,
            IllegalStateException, IOException {

        setContentView(R.layout.activity_android_building_music_player);
        Log.d("ringtone", "playSong :: " + path);

        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        acv(path);
        abc();
        cde();
    }

    public void acv(String path) {
        getInit();

        metaRetriver = new MediaMetadataRetriever();
        metaRetriver.setDataSource(path);
        try {
            art = metaRetriver.getEmbeddedPicture();
            Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
            album_art.setImageBitmap(songImage);
            album.setText(metaRetriver
                    .extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
            artist.setText(metaRetriver
                    .extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
        } catch (Exception e) {
            album_art.setBackgroundColor(Color.GRAY);
            album.setText("Unknown Album");
            artist.setText("Unknown Artist");
        }

    }

    public void getInit() {
        album_art = (ImageView) findViewById(R.id.coverart1);
        album = (TextView) findViewById(R.id.Album);
        artist = (TextView) findViewById(R.id.artist_name);
    }


    public void abc() {
        ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
        btnPlay1.setBackgroundColor(Color.TRANSPARENT);
        btnPlay1.setOnClickListener(
                new View.OnClickListener() {
                    public void onClick(View v) {
                        if (mMediaPlayer.isPlaying()) {
                            mMediaPlayer.pause();
                        } else {
                            mMediaPlayer.start();
                        }

                    }
                });
    }




 public void cde() {
    ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);  //this is the button for playing next song.
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            try {
                        currentPosition=currentPosition+1;
                    playSong(path + songs.get(currentPosition));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
}
}

2 Answers2

1

Add this in onCreate method:

Bundle bundle = getIntent().getExtras();
position = bundle.getInt("position");

And change next button listener to

btnNext.setOnClickListener(new View.OnClickListener()    //this is the button                                          

                @Override
                public void onClick(View arg0) {
                   if (mMediaPlayer!= null && mMediaPlayer.isPlaying()) {
                     mMediaPlayer.stop();
                   }
                   uri = Uri.parse(mAudioPath[position + 1]);
                   mMediaPlayer.setDataSource(getApplicationContext(), uri);
                   mMediaPlayer.prepare();              
                   mMediaPlayer.start();
                }
            });
ChetanKN
  • 11
  • 3
  • There are no bundles involved in the code posted by OP. You have to explain what it does, otherwise this is code that isn't used – Zoe Jul 22 '17 at 12:44
  • "currentPosition" variable is initialized to 0 in onclick method. Can you explain how it will get current position value? – ChetanKN Jul 22 '17 at 12:53
  • A bundle will still not fix it – Zoe Jul 22 '17 at 13:30
1
    int currentPosition = 0;
    if (++currentPosition >= songs.size()) {
        currentPosition = 0;
    } else
            try {
                playSong(path + songs.get(currentPosition));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
    }

The above code is your code from the onClick method.

As you can see, you are initializing the currentPosition inside onClick.

So to show you what this implies:

onClick -> position = 0 -> position++ (position = 1) -> playSong(songUri)

When you want:

onClick -> position++ -> playSong(songUri)

So, before setting the onCLickListener, you add:

currentPosition = 0;

currentPosition is declared in the class now, so make sure you add it. It should look like this:

int currentPosition;

..other code

public void cde(){
    ..code here
    currentPosition = 0;
   ... set onClickListener
}

Remove int currentPosition = 0; from the onClick method.

I assume there is a position 0 as well. Here is the refactored code that would handle that:

try {
    playSong(path + songs.get(currentPosition));

    if (++currentPosition >= songs.size()) {
        currentPosition = 0;
    } 
} catch (IOException ex) {
    ex.printStackTrace();
}

The above code is addressing another issue you would be likely to meet. Song 0 would never play on the first round.

Another thing you want to check for (not giving you the code for it as it is easy) is to not play or allow next song if there are no songs. If songs.size == 0 it would never play but set the position to 0 over and over.

Zoe
  • 27,060
  • 21
  • 118
  • 148