I am working on an app that is basically a music library and for each song, when you press button play, the song starts playing. For the moment, my library has 3 items and I am trying to play "sound.mp3", which is in res/raw, for the 3 of them (for the moment).
My problem is when I try to reference the clip, I have a red underline under "this, R.raw.sound". I saw that in most cases "create" is called in onCreate, but in my case, this class in not an activity so I cannot do that ...
Can you guys help me with that? :)
public class ClipsAdapter extends RecyclerView.Adapter<ClipsAdapter.MyViewHolder> {
private final List<Clips> clip2 = Arrays.asList(
new Clips("Clip 1", "Artist 1"),
new Clips("Clip 2", "Artist 2"),
new Clips("Clip 3", "Artist 3")
);
public class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView title;
private final TextView author;
private final ImageView play;
private Clips currentClip;
MediaPlayer mediaPlayer = new MediaPlayer();
public MyViewHolder(final View itemView) {
super(itemView);
title = ((TextView) itemView.findViewById(R.id.title));
author = ((TextView) itemView.findViewById(R.id.author));
play = ((ImageView) itemView.findViewById(R.id.play));
}
public void display(RandomClips RandomClip) {
currentRandomClip = RandomClip;
title.setText(RandomClip.title);
author.setText(RandomClip.author);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Play clip: " + currentClip.title);
mediaPlayer.create(this, R.raw.sound);
if (mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.reset();
Log.d(TAG, currentRandomClip.title + " has stopped");
}
else
{
mediaPlayer.start();
Log.d(TAG, currentRandomClip.title + " is playing");
}
}
});
}
}
}
mediaPlayer.create() requests for a context and the file to play.
The 'this' you are passing as an argument is not a Context (you are in an anonymous class) and therefore you get an error.
You should pass a context.
Simply pass your activity's context when instantiating your ClipsAdapter.
So in your activity instantiate your adapter :
clipsAdapter = new ClipsAdapter(this);
In your ClipsAdapter class, create a constructor with one parameter :
public ClipsAdapter(YourActivity activity) {
this.activity = activity;
}
Finally :
mediaPlayer.create(activity, R.raw.sound);