Search code examples
androidlistviewmedia-player

media player in listview


I reproduce sound in listeview . I have a custom adapter , but it always fails the line where I put the int with the resources of the mp3 ! ono sure I'm perdnto something but do not know what ! advice on how to solve? thank you

public class Adapter_animal extends ArrayAdapter<String>  {
private final Activity context;
private final String[] animal;
private final int[] animal_id;
private MediaPlayer mp;


public Adapter_animal(Activity context, int mylist, String[] animal, int[] animal_id) {
    super(context, R.layout.mylist, animal);
    // TODO Auto-generated constructor stub
    this.context=context;
    this.animal = animal;

    this.animal_id = animal_id;
}

public View getView(final int position,View view,ViewGroup parent) {
    LayoutInflater inflater=context.getLayoutInflater();
    View rowView=inflater.inflate(R.layout.mylist, null,true);

    TextView txtTitle = (TextView) rowView.findViewById(R.id.titolo);
    txtTitle.setText(animal[position]);

    FloatingActionButton btn = (FloatingActionButton) rowView.findViewById(R.id.f1_btn);

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            stopPlaying();
            mp = MediaPlayer.create(Adapter_animal.this, animal_id);  //error in this line "cannot resolve method
            mp.start();
        }

    });











    return rowView;

};
private void stopPlaying() {
    if (mp != null) {
        mp.stop();
        mp.release();
        mp = null;
    }
}

string

static String[] animal={
        "animale",
        "animale2",
        "animale3",

};

static int[] animal_id={
        R.raw.a11_ovation,


};

Solution

  • You're passing an array to a method that expects a single resource id...

    Documentation:

    public static MediaPlayer create (Context context, int resid)

    Convenience method to create a MediaPlayer for a given resource id. On success, prepare() will already have been called and must not be called again.

    When done with the MediaPlayer, you should call release(), to free the resources. If not released, too many MediaPlayer instances will result in an exception.

    Note that since prepare() is called automatically in this method, you cannot change the audio stream type (see setAudioStreamType(int)), audio session ID (see setAudioSessionId(int)) or audio attributes (see setAudioAttributes(AudioAttributes) of the new MediaPlayer.

    Parameters

    context - the Context to use

    resid - the raw resource id (R.raw.<something>) for the resource to use as the datasource

    Returns

    MediaPlayer - a MediaPlayer object, or null if creation failed