Tuesday, June 16, 2009

Displaying the List of music files Stored in SD card and playing music in the background

The foolowing example used to list all the music files stored in SDcard and you can play the music
in the backgroung by selecting the file from list.

main.xml
--------
<?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical" android:layout_width="fill_parent"
      android:layout_height="fill_parent">
      < ListView
            android:id="@+id/PhoneMusicList"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
</LinearLayout>

MusicActivity.java
-------------------
package sample.music;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MusicActivity extends Activity {
      ListView musiclist;
      Cursor musiccursor;
      int music_column_index;
      int count;
      MediaPlayer mMediaPlayer;

      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            init_phone_music_grid();
      }

      private void init_phone_music_grid() {
            System.gc();
            String[] proj = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE };
            musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
            count = musiccursor.getCount();
            musiclist = (ListView) findViewById(R.id.PhoneMusicList);
            musiclist.setAdapter(new MusicAdapter(getApplicationContext()));

            musiclist.setOnItemClickListener(musicgridlistener);
            mMediaPlayer = new MediaPlayer();
      }

      private OnItemClickListener musicgridlistener = new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position,
long id) {
                  System.gc();
                  music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                  musiccursor.moveToPosition(position);
                  String filename = musiccursor.getString(music_column_index);

                  try {
                        if (mMediaPlayer.isPlaying()) {
                              mMediaPlayer.reset();
                        }
                        mMediaPlayer.setDataSource(filename);
                        mMediaPlayer.prepare();
                        mMediaPlayer.start();
                  } catch (Exception e) {

                  }
            }
      };

      public class MusicAdapter extends BaseAdapter {
            private Context mContext;

            public MusicAdapter(Context c) {
                  mContext = c;
            }

            public int getCount() {
                  return count;
            }

            public Object getItem(int position) {
                  return position;
            }

            public long getItemId(int position) {
                  return position;
            }

            public View getView(int position, View convertView, ViewGroup parent) {
                  System.gc();
                  TextView tv = new TextView(mContext.getApplicationContext());
                  String id = null;
                  if (convertView == null) {
                        music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
                        musiccursor.moveToPosition(position);
                        id = musiccursor.getString(music_column_index);
                        music_column_index = musiccursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
                        musiccursor.moveToPosition(position);
                        id += " Size(KB):" + musiccursor.getString(music_column_index);
                        tv.setText(id);
                  } else
                        tv = (TextView) convertView;
                  return tv;
            }
      }
}

39 comments:

  1. This is the first tutorial I see that doesn't need debug! (except removing spaces in the xml file, one before LinearLayout and One before ListView)

    Really helped me, thanks a lot!

    ReplyDelete
  2. Hi,
    when i click the list item it's not respond for me.pls help me ya.

    ReplyDelete
  3. in a similar way i want to uplopad my audio/video file to website server on clicking a file from the list.pls help

    ReplyDelete
  4. I tried this as my first Android App. It works! I get a scrollable list of my songs.
    But when I scroll up and down, the list is mixed up. I tap on an title but it playes the wrong one. Each time I go back to the top of the list, a different song is displayed as the first song.
    What is wrong?

    ReplyDelete
  5. why i copy your project but error !! :(
    please help me !! thanks a lot you!!
    (sorry i speak E very bad)

    ReplyDelete
  6. public View getView(int position, View convertView, ViewGroup parent) {
    System.gc();
    String id = null;
    TextView tv;
    if (convertView == null) {
    tv = new TextView(mContext.getApplicationContext());
    } else{
    tv = (TextView) convertView;
    }
    musiccursor.moveToPosition(position);
    music_column_index = musiccursor
    .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
    id = musiccursor.getString(music_column_index);
    music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
    id += " Size(KB):" + musiccursor.getString(music_column_index);
    tv.setText(id);
    return tv;
    }

    ReplyDelete
  7. thank you, u saved the day for me............:)
    Fabulous work......

    ReplyDelete
  8. Thank you for the code, i was searching this for since last 15 days.

    Once again thank you!!! it worked for me.

    ReplyDelete
  9. hi i'm trying to play sdcard songs in a service. but it is giving me null pointer exception. please help....

    ReplyDelete
  10. hai, first thanks for this tutorial..
    when i tried to execute it first time iam getting result..
    but second time iam getting blank screen on my emulator......
    pls help me......... :P
    thanks in advance.........

    ReplyDelete
  11. Nice Work....!!
    Thanks for this code...!!
    It helped me a lot in my work...!!

    ReplyDelete
  12. The said thing about these ... codes that are being posted is, the people trying to Use them (YOU), have no faith in what your doing. In order to make a vast array of these "FREE Online CODES" to work ... yall need to try them on a ACTUAL PHONE ... and if your to scared to do so, go back to Windows OS ... lol ... code worked perfectly for me (On the Actual Phone).

    ReplyDelete
  13. i want to seperate songs according to albums ..can you help...

    ReplyDelete
  14. i get force close error when i run this project

    ReplyDelete
  15. i get force close error when i run this project too ,, i use an emulator not a real phone ,, is this the problem here ?

    ReplyDelete
  16. where to copy mp3 file in my emulator any help would be greatly appreciated

    ReplyDelete
  17. really awasome codding.
    you saved my time and

    ReplyDelete
  18. my self rahul.
    so thnxs brd fr providing it.!!

    ReplyDelete
  19. can u provide me the coding of hws i can get my mp3 file from SDCArd..plz
    send me coding at rahul.iec44@gmail.com

    ReplyDelete
  20. i am using you're code to also play the files display.
    now i am trying to get the player to skip the song to the next song.
    but....it's not working :D
    do you have any ideas on how to do this?
    thanks

    ReplyDelete
  21. I tried this as my first Android App. It works! I get a scrollable list of my songs.
    But when I scroll up and down, the list is mixed up. I tap on an title but it playes the wrong one. Each time I go back to the top of the list, a different song is displayed as the first song.
    What is wrong?


    plz help me

    ReplyDelete
  22. play wrong song, not playing the selected song. pls hlp..

    ReplyDelete
  23. Replies
    1. haii iam getting errors...please send me the total zip file to my mail id ..pls pls ...sel.ajaykumar@gmail.com

      Delete
  24. the song does not stop..:( plz help
    and can some1 post the code for listing files according to artist and albums...

    ReplyDelete
  25. 22 g code te tuhada aat e g keep it up

    ReplyDelete
  26. initially i create sample project and then two files MusicActivity.java and main.xml

    when i run sample project then nothing is display (how to make it functional)

    ReplyDelete
    Replies
    1. You just have to add file in sd card not in MusicActivity.java. then change to managedQuery to getContentResolver().query. I hope it will work!

      Delete
  27. It Works for me! I woonder how it can play in background without service. Please can you show me de lines that enable it to do that?

    ReplyDelete
    Replies
    1. haii iam getting errors...please send me the total zip file to my mail id ..pls pls ...sel.ajaykumar@gmail.com

      Delete
    2. hi iam getting white blank thats it plz help me out

      Delete
  28. Thanks you. The code works 90%. However the remaining problems when i run is:
    1. Can not play more than 3 song. The root of problem comes from the failure in mMediaPlayer.setDataSource(filename);

    ReplyDelete
  29. I have a android phone online store and i want to create some blogs to improve my traffic but i was see your blogs and i was happy to get some idea to your blogs thanks a lot you create a good blogs i hope you do more blogs ^^

    ReplyDelete
  30. how should display mp3 file in View,
    in your example you are using PhoneMusicList

    ReplyDelete
  31. very tanks to you,,

    ReplyDelete
  32. System.gc();

    is showing error.. can any one help me plz

    ReplyDelete