简体   繁体   中英

How to get song from list view in item click in android

i have made android application in which i read all audio songs from mobile storage and add all songs to customize list view. in my list view there is simple one text view in which songs are placed now i want to add click listener to list and get these songs from list view and passed to another activity for playing songs. i have two classes MainActivity.java

public class MainActivity extends AppCompatActivity {
ListView lv;
String[] items;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv = (ListView) findViewById(R.id.lvPlaylist);

    final ArrayList<File> mySongs = findSongs(Environment.getExternalStorageDirectory());
    items = new String[mySongs.size()];
    for (int i = 0; i < mySongs.size(); i++) {
        //toast(mySongs.get(i).getName().toString());
        items[i] = mySongs.get(i).getName().toString().replace(".mp3", "").replace(".wav", "");
    }

    ArrayAdapter<String> adp = new ArrayAdapter<String>(getApplicationContext(), R.layout.song_layout, R.id.textView, items);
    lv.setAdapter(adp);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long l) {

            Intent intent = new Intent(MainActivity.this,Player.class);
            intent.putExtra("pos",position);
            intent.putExtra("songList",mySongs);
            startActivity(intent);
            //  startActivity(new Intent(getApplicationContext(),Player.class).putExtra("pos",position).putExtra("songlist",mySongs));

        }
    });

}

public ArrayList<File> findSongs(File root) {
    ArrayList<File> al = new ArrayList<File>();
    File[] files = root.listFiles();
    for (File singleFile : files) {
        if (singleFile.isDirectory() && !singleFile.isHidden()) {
            al.addAll(findSongs(singleFile));

        } else {
            if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")) {
                al.add(singleFile);
            }
        }

    }
    return al;
}

public void toast(String text) {
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}

}

here is Palyer.java

public class Player extends AppCompatActivity implements View.OnClickListener{
static MediaPlayer mp;
ArrayList mySongs;
int position;
Uri u;
Thread updateSeekBar;


SeekBar sb;
Button btPlay, btFF, btFB, btPv, btNxt;

MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_player);

    btPlay = (Button)findViewById(R.id.btPlay);
    btFF = (Button)findViewById(R.id.btFF);
    btFB = (Button)findViewById(R.id.btFB);
    btPv = (Button)findViewById(R.id.btPv);
    btNxt = (Button)findViewById(R.id.btNxt);

    btPlay.setOnClickListener(this);
    btFF.setOnClickListener(this);
    btFB.setOnClickListener(this);
    btPv.setOnClickListener(this);
    btNxt.setOnClickListener(this);

    sb = (SeekBar)findViewById(R.id.seekBar);
    updateSeekBar = new Thread(){
        @Override
        public void run() {
            //super.run();
            int totalDuration = mp.getDuration();
            int currentPosition = 0;
            sb.setMax(totalDuration);
            while(currentPosition<totalDuration){
                try{
                    sleep(500);
                    currentPosition= mp.getCurrentPosition();
                    sb.setProgress(currentPosition);
                } catch(InterruptedException e){
                    e.printStackTrace();

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

    Intent i = getIntent();
    mySongs.add(i.getStringExtra("songList"));
    position=i.getIntExtra("pos",0);
    u = Uri.parse(mySongs.get(position).toString());
    mp = MediaPlayer.create(getApplicationContext(),u );

    mp.release();
    mp.prepareAsync();

    mp.start();
    sb.setMax(mp.getDuration());

   updateSeekBar.start();
    sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mp.seekTo(seekBar.getProgress());

        }
    });


}

@Override
public void onClick(View view) {
    int id = view.getId();
    switch (id){
        case R.id.btPlay:
            if(mp.isPlaying()){
                btPlay.setText(">");
                mp.pause();
            }
            else{
                mp.start();
                btPlay.setText("||");
            }
            break;
        case R.id.btFF:
            mp.seekTo(mp.getCurrentPosition()+5000);
            break;
        case R.id.btFB:
            mp.seekTo(mp.getCurrentPosition()-5000);
            break;
        case R.id.btNxt:
           mp.stop();
            mp.release();
            position = (position+1)%mySongs.size();
            u = Uri.parse(mySongs.get(position).toString());
            mp = MediaPlayer.create(getApplicationContext(),u );
            mp.start();
            sb.setMax(mp.getDuration());
            break;
        case R.id.btPv:
            mp.stop();
            mp.release();
            position = (position-1<0)? mySongs.size()-1: position-1;
            /*if(position-1<0){
                position = mySongs.size()-1;
            }
            else{
                position = position-1;
            }*/
            u = Uri.parse(mySongs.get(position).toString());
            mp = MediaPlayer.create(getApplicationContext(),u );
            mp.start();
            sb.setMax(mp.getDuration());
            break;
    }

}

}

when i launched my application and click on the songs in list view my application is crashed can anybody help to get song from my list view in item click listener thanks.

 Make your songs arraylist serializable as:
 public class SongsList implements Serializable
 /// getter and setter
 From Songs Files add object to SongList class then send this class 
 as:
 Intent intent = new Intent(SourceActivity.this,  
 argetActivity.class);
 intent.putExtra("SongListExtra", songList);
 On receiving activity:
 ArrayList<SongList> songlist = new ArrayList<SongList>();
 songlist = (ArrayList<SongList>) 
 getIntent().getSerializableExtra("SongListExtra");
 Instead of sending songList to player activity you can send that 
 particular song details on list item clicked according to position.
 Hope it helps..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM