Friday, July 31, 2015

// //

Listing all audio in sdcard using listview

hi, guys today i want to show you how to easily show the items
 from the sdcard into the listview..

Okay so let's get started...

Now make an xml in layout folder.




And then make another xml,
this xml contains only textview and responsible of displaying file names from sdcard:


Now make an activity file :
I've put comments on this code so that you may read it and understand the code.
import java.util.ArrayList;
import java.util.HashMap;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class PlayListActivity extends ListActivity {
 // Songs list
 public ArrayList> songsList = new ArrayList>();

 Button display;
 public void onCreate(Bundle savedInstanceState) {
  display = (Button) findViewById(;

  final ArrayList> songsListData = new ArrayList>();

  SongsManager plm = new SongsManager();
  this.songsList = plm.getPlayList();

  // Adding menuItems to ListView
  final ListAdapter adapter = new SimpleAdapter(this, songsListData,
    R.layout.playlist_item, new String[] { "songTitle" }, new int[] { });
   display.setOnClickListener(new Button.OnClickListener(){

      public void onClick(View v) {
       // TODO Auto-generated method stub
    // get all songs from sdcard

     // looping through playlist
     for (int i = 0; i < songsList.size(); i++) {
      // creating new HashMap
      HashMap song = songsList.get(i);

      // adding HashList to ArrayList



And then make another activity file:
import java.util.ArrayList;
import java.util.HashMap;

public class SongsManager {
 // SDCard Path
 //choose your path for me i choose sdcard
 final String MEDIA_PATH = new String("/sdcard/");
 private ArrayList> songsList = new ArrayList>();
 // Constructor
 public SongsManager(){
  * Function to read all mp3 files from sdcard
  * and store the details in ArrayList
  * */
 public ArrayList> getPlayList(){
  File home = new File(MEDIA_PATH);

  if (home.listFiles(new FileExtensionFilter()).length > 0) {
   for (File file : home.listFiles(new FileExtensionFilter())) {
    HashMap song = new HashMap();
    song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
    song.put("songPath", file.getPath());
    // Adding each song to SongList
  // return songs list array
  return songsList;
  * Class to filter files which are having .mp3 extension
  * */
 //you can choose the filter for me i put .mp3
 class FileExtensionFilter implements FilenameFilter {
  public boolean accept(File dir, String name) {
   return (name.endsWith(".mp3") || name.endsWith(".MP3"));

And thats it! you can change the filter if you want!
Now run it on your real device!i
You may also like: Display more than one extensions in listview