Search code examples
androidlistviewsd-card

Display all music on SD card


I'm using code form this page:

http://z4android.blogspot.com/2011/06/displaying-list-of-music-files-stored.html

The code is working, but not soo good. When I'm trying to scroll down, the ListView keeps repeating the songs in the list.

I have been looking for some alternative code, but I have not found any.

Thanks for any help.


Solution

  • I'm not entirely sure exactly what causes the problems you mention, but try this code.

    private MediaPlayer mMediaPlayer;
    private String[] mMusicList;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
      mMediaPlayer = new MediaPlayer();
    
      ListView mListView = (ListView) findViewById(R.id.listView1);
    
      mMusicList = getMusic();
    
      ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this,
      android.R.layout.simple_list_item_1, mMusicList);
      mListView.setAdapter(mAdapter);
    
      mListView.setOnItemClickListener(new OnItemClickListener() {
    
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {
          try {
            playSong(mMusicList[arg2]);
          } catch (IllegalArgumentException e) {
            e.printStackTrace();
          } catch (IllegalStateException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      });
    }
    
    private String[] getMusic() {
      final Cursor mCursor = managedQuery(
      MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
      new String[] { MediaStore.Audio.Media.DISPLAY_NAME }, null, null,
      "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
    
      int count = mCursor.getCount();
    
      String[] songs = new String[count];
      int i = 0;
      if (mCursor.moveToFirst()) {
        do {
          songs[i] = mCursor.getString(0);
          i++;
        } while (mCursor.moveToNext());
      }
    
      mCursor.close();
    
      return songs;
    }
    
    private void playSong(String path) throws IllegalArgumentException,
    IllegalStateException, IOException {
      String extStorageDirectory = Environment.getExternalStorageDirectory()
      .toString();
    
      path = extStorageDirectory + File.separator + path;
    
      mMediaPlayer.reset();
      mMediaPlayer.setDataSource(path);
      mMediaPlayer.prepare();
      mMediaPlayer.start();
    }