List All Mp3 files in android - android

I am developing music player in android but stuck in reading MP3 files.
here is my code to read all mp3 files. but its not returing any files from device(although there are some files which i copied using adb). I also want it to list using Album, artist etc. please help in this.
final String MEDIA_PATH = Environment.getExternalStorageDirectory()+"";
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
public SongsManager(){
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList(){
File home = new File(MEDIA_PATH);
//if (home.listFiles(new FileExtensionFilter()).length > 0) {
if (home.listFiles(new FileExtensionFilter())!=null) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which are having .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}

here I've modified your getPlayList() method. look into it.
ArrayList<HashMap<String,String>> getPlayList(String rootPath) {
ArrayList<HashMap<String,String>> fileList = new ArrayList<>();
try {
File rootFolder = new File(rootPath);
File[] files = rootFolder.listFiles(); //here you will get NPE if directory doesn't contains any file,handle it like this.
for (File file : files) {
if (file.isDirectory()) {
if (getPlayList(file.getAbsolutePath()) != null) {
fileList.addAll(getPlayList(file.getAbsolutePath()));
} else {
break;
}
} else if (file.getName().endsWith(".mp3")) {
HashMap<String, String> song = new HashMap<>();
song.put("file_path", file.getAbsolutePath());
song.put("file_name", file.getName());
fileList.add(song);
}
}
return fileList;
} catch (Exception e) {
return null;
}
}
you can get the song name and song path like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ArrayList<HashMap<String,String>> songList=getPlayList("/storage/sdcard1/");
if(songList!=null){
for(int i=0;i<songList.size();i++){
String fileName=songList.get(i).get("file_name");
String filePath=songList.get(i).get("file_path");
//here you will get list of file name and file path that present in your device
log.e("file details "," name ="+fileName +" path = "+filePath);
}
}
}
Note: use "/storage/sdcard1/" for reading files from sdCard and use Environment.getExternalStorageDirectory().getAbsolutePath() for reading files from phone memory
Hope this will help you.

Hope you already found your answer but may be this is better and if you wants to try, Here is your solution use the following code to Read the MP3 file from the Specific Folder or All files,
First of all Create 1 Model class as Given Below, to GET and SET Files in list.
AudioModel.class
public class AudioModel {
String aPath;
String aName;
String aAlbum;
String aArtist;
public String getaPath() {
return aPath;
}
public void setaPath(String aPath) {
this.aPath = aPath;
}
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
public String getaAlbum() {
return aAlbum;
}
public void setaAlbum(String aAlbum) {
this.aAlbum = aAlbum;
}
public String getaArtist() {
return aArtist;
}
public void setaArtist(String aArtist) {
this.aArtist = aArtist;
}
}
Now We have our Model Class, use the below code to Read the all MP3 files from your Folder or device.
This will return list of all MP3 Files with Music NAME, PATH, ARTIST, ALBUM. if you want more details, please refer the documentation for Media.Store.Audio
public List<AudioModel> getAllAudioFromDevice(final Context context) {
final List<AudioModel> tempAudioList = new ArrayList<>();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.ArtistColumns.ARTIST,};
Cursor c = context.getContentResolver().query(uri, projection, MediaStore.Audio.Media.DATA + " like ? ", new String[]{"%yourFolderName%"}, null);
if (c != null) {
while (c.moveToNext()) {
AudioModel audioModel = new AudioModel();
String path = c.getString(0);
String album = c.getString(1);
String artist = c.getString(2);
String name = path.substring(path.lastIndexOf("/") + 1);
audioModel.setaName(name);
audioModel.setaAlbum(album);
audioModel.setaArtist(artist);
audioModel.setaPath(path);
Log.e("Name :" + name, " Album :" + album);
Log.e("Path :" + path, " Artist :" + artist);
tempAudioList.add(audioModel);
}
c.close();
}
return tempAudioList;
}
To read the files of a specific folder, use this query (write the target folder name in the query)
Cursor c = context.getContentResolver().query(uri,
projection,
MediaStore.Audio.Media.DATA + " like ? ",
new String[]{"%yourFolderName%"}, // yourFolderName
null);
If you want all the files on the device, use this query:
Cursor c = context.getContentResolver().query(uri,
projection,
null,
null,
null);
Don't forget to add the storage permission.

Try This
String path;
File sdCardRoot = Environment.getExternalStorageDirectory();
File dir = new File(sdCardRoot.getAbsolutePath() + "/yourDirectory/");
if (dir.exists()) {
if (dir.listFiles() != null) {
for (File f : dir.listFiles()) {
if (f.isFile())
path = f.getName();
if (path.contains(".mp3")) {
yourArrayList.add(path);
}
}
}
}

This function will provide you a list of all audio files paths in device storage
public ArrayList<String> getAllMusic(){
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Audio.AudioColumns.DATA};
ArrayList<String> songs_path = new ArrayList<>();
Cursor c = context.getContentResolver().query(uri, projection, null,null,null);
if (c != null) {
while (c.moveToNext()) {
String path = c.getString(0);
songs_path.add(path);
}
c.close();
}
return songs_path;
}
ArrayList<String> allSongs = getAllMusic();
File song = new File(allSongs.get(0));

Related

How to delete image file from Android Internal when path is stored in SQLite DB

I Know this is already answered question.But I'm unable to figure it out when using SQLite DB. My app captures some documents and will be stores in phone memory. I'm using SQLite DB in my app which stores the path of the above image. How can i delete the image from phone memory if i delete the image in SQLite DB.
String photoPath = cursor.getString(i_COL_PICTURE);
--My path is
`"content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F153/ORIGINAL/NONE/1743496576"
`
When you want delete some file in your storage, Just do this.
File file = new File(yourFilePathHere);
deleted = file.delete();
I am considering you have required permissions because you are able to write files in storage.
Edit
You are using MediaStore for getting images. So now when you want delete file you should delete file from MediaStore also. I have a method which will help you.
public static int deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
String canonicalPath;
try {
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
canonicalPath = file.getAbsolutePath();
}
final Uri uri = MediaStore.Files.getContentUri("external");
final int result = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
if (result == 0) {
final String absolutePath = file.getAbsolutePath();
if (!absolutePath.equals(canonicalPath)) {
int deletedRow = contentResolver.delete(uri,
MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
return deletedRow;
}
} else return result;
return result;
}
Call it in your Activity like
deleteFileFromMediaStore(getContentResolver(), fileToDelete)
Note Check if you are getting absolute path by MediaStore. Here is my method to get all gallery images if you have problem with your code.
public static ArrayList<ModelBucket> getImageBuckets(Context context) {
ArrayList<ModelBucket> list = new ArrayList<>();
String absolutePathOfImage;
String absoluteFolder;
boolean same_folder = false;
int pos = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = context.getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
if (cursor == null) return null;
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
absoluteFolder = cursor.getString(column_index_folder_name);
Log.d("Column", absolutePathOfImage);
Log.d("Folder", absoluteFolder);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getFolderName().equals(absoluteFolder)) {
same_folder = true;
pos = i;
break;
} else {
same_folder = false;
}
}
if (same_folder) {
ArrayList<String> al_path = new ArrayList<>(list.get(pos).getAllFilesPath());
al_path.add(absolutePathOfImage);
list.get(pos).setAllFilesPath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
ModelBucket modelBucket = new ModelBucket();
modelBucket.setFolderName(absoluteFolder);
modelBucket.setAllFilesPath(al_path);
list.add(modelBucket);
}
}
return list;
}
here ModelBucket.class is a model class.
public class ModelBucket {
String folderName;
ArrayList<String> allFilesPath;
ArrayList<ModelFile> files;
// make getter setter
}
before deleting the image get the path of the image and pass the path to below code
File fdelete = new File(path);
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + path);
} else {
System.out.println("file not Deleted :" + path);
}
}
after this remove the path from sqlite db
If you have your Uri pointing to the file you can do :
String pathToFile = myUri.getEncodedPath(); // this gives your the real path to the file, like /emulated/0/sdcard/myImageFile.jpg
File file = new File(pathToFile);
if(file.exists()){
file.delete();
}

How to get list of directory containing images in android

I have used following code to get list of directories
String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
ROOT_DIR is passed is as string
public static ArrayList<String> getDirectoryPaths(String directory) {
ArrayList<String> pathArray = new ArrayList<>();
File file = new File(directory);
File[] listfiles = file.listFiles();
if (listfiles != null) {
for (int i = 0; i < listfiles.length; i++) {
if (listfiles[i].isDirectory()) {
pathArray.add(listfiles[i].getAbsolutePath());
}
}
}
return pathArray;
}
`
It returns all directories path but i want to get the path of the directories containing images only like it shows in gallery Eg (Camera, WhatsAppImages, hike,...); I want to get path of all of them.
Any ideas?
Try this:
Create a Bucket Class
public class Bucket {
private String name;
private String firstImageContainedPath;
public Bucket(String name, String firstImageContainedPath) {
this.name = name;
this.firstImageContainedPath = firstImageContainedPath;
}
public String getName() {
return name;
}
public String getFirstImageContainedPath() {
return firstImageContainedPath;
}
}
Then, Add this method, it is going to return all the buckets where there are Images.
public static List<Bucket> getImageBuckets(Context mContext){
List<Bucket> buckets = new ArrayList<>();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String bucketPath = cursor.getString(cursor.getColumnIndex(projection[0]));
String fisrtImage = cursor.getString(cursor.getColumnIndex(projection[1]));
file = new File(fisrtImage);
if (file.exists() && !bucketSet.contains(bucketName)) {
buckets.add(new Bucket(bucketName, fisrtImage));
}
}
cursor.close();
}
return buckets;
}
Finally, create your custom spinner item and fill your spinner with an adapter.
Next Step is to fill the gridview with images from the selected bucket.
This method is going to return all the images according the bucketpath.
public List<String> getImagesByBucket(#NonNull String bucketPath){
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.DATA};
String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME+" =?";
String orderBy = MediaStore.Images.Media.DATE_ADDED+" DESC";
List<String> images = new ArrayList<>();
Cursor cursor = mContext.getContentResolver().query(uri, projection, selection,new String[]{bucketPath}, orderBy);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String path = cursor.getString(cursor.getColumnIndex(projection[0]));
file = new File(path);
if (file.exists() && !images.contains(path)) {
images.add(path);
}
}
cursor.close();
}
return images;
}
Finally, create your adapter and fill your gridview.
I hope, It can help you.

How can I get all audio files from the SD card on Android?

I want to write a class which gets all the MP3 files from the whole SD card. But actually it only gets the audio files laying directly on the SD card. So it doesn’t search trough sub folders. I'd like to use Mediastore, but I don’t get it to an arraylist.
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import de.me.musicplayer.SongsManager.FileExtensionFilter;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
public class SongsManager {
final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
public SongsManager(){
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList(){
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which are having .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
}
final String MEDIA_PATH = Environment.getExternalStorageDirectory()
.getPath() + "/";
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private String mp3Pattern = ".mp3";
// Constructor
public SongsManager() {
}
/**
* Function to read all mp3 files and store the details in
* ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList() {
System.out.println(MEDIA_PATH);
if (MEDIA_PATH != null) {
File home = new File(MEDIA_PATH);
File[] listFiles = home.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file : listFiles) {
System.out.println(file.getAbsolutePath());
if (file.isDirectory()) {
scanDirectory(file);
} else {
addSongToList(file);
}
}
}
}
// return songs list array
return songsList;
}
private void scanDirectory(File directory) {
if (directory != null) {
File[] listFiles = directory.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file : listFiles) {
if (file.isDirectory()) {
scanDirectory(file);
} else {
addSongToList(file);
}
}
}
}
}
private void addSongToList(File song) {
if (song.getName().endsWith(mp3Pattern)) {
HashMap<String, String> songMap = new HashMap<String, String>();
songMap.put("songTitle",
song.getName().substring(0, (song.getName().length() - 4)));
songMap.put("songPath", song.getPath());
// Adding each song to SongList
songsList.add(songMap);
}
}
You can also fetch using the ContentResolver class.
I have done like this and it's working fine.
public void getSongListFromStorage() {
// Retrieve song information
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst()) {
// Get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
// Add songs to the list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
} while (musicCursor.moveToNext());
}
}
This code will give you an arrayList of hash maps whose content is the song title as well as the song's absolute path.
public ArrayList<HashMap<String, String>> getAudioList() {
ArrayList<HashMap<String, String>> mSongsList = new ArrayList<HashMap<String, String>>();
Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATA }, null, null, null);
int count = mCursor.getCount();
System.out.println("total no of songs are=" + count);
HashMap<String, String> songMap;
while (mCursor.moveToNext()) {
songMap = new HashMap<String, String>();
songMap.put("songTitle",mCursor.getString(mCursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)));
songMap.put("songPath", mCursor.getString(mCursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
mSongsList.add(songMap);
}
mCursor.close();
return mSongsList;
}
private void getallaudio()
{
String[] STAR = { "*" };
controller.audioWrapper.clear();
Cursor audioCursor = ((Activity) cntx).managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
if (audioCursor != null)
{
if (audioCursor.moveToFirst())
{
do
{
String path = audioCursor.getString(audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
audioWrapper.add(new MediaWrapper(new File(path).getName(), path, "Audio",false));
// Log.i("Audio Path",path);
}while (audioCursor.moveToNext());
}
// audioCursor.close();
}
}

Getting all MP3 files on the external card

What i'm trying to achieve is getting all the mp3 files'URL and Title in an arraylist to return it. All from the folder: /ext_card/Music/ and all subfolders.
the options i've explored all seem to get stuck, and all the answers i've looked up on the internet point to mediastore, but i have no idea how to use it
And don't give me the RTFM bullshit, because the explanations i've found for mediastore is retarded at best.
SO can anyone please help me out or give me an example of a simple working mediastore query for all mp3 files?
Use this it will help you to get all MP3 Song from SD CARD
private static ArrayList<genericSongClass> songs = null;
public void BindAllSongs() {
/** Making custom drawable */
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
final String[] projection = new String[] {
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
try {
// the uri of the table that we want to query
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
// query the db
cursor = getBaseContext().getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
songs = new ArrayList<genericSongClass>(cursor.getCount());
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
GSC = new genericSongClass();
GSC.songTitle = cursor.getString(0);
GSC.songArtist = cursor.getString(1);
GSC.songData = cursor.getString(2);
songs.add(GSC);
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public class genericSongClass {
String songTitle = "";
String songArtist = "";
String songData = "";
String isChecked = "false";
}
Here is a recursive way to do such thing,
getMp3s(Arraylist<File> list, File dir){
File[] files = dir.listFiles();
for(File file : files){
if(file.isDirectory()){
getMp3s(list, file);
}else{
//add mp3s to list here
}
}
}

Get path of song from SD card in android

In my android application I want to fetch song from SD card but I am not able to get the path of that particular file.I am using android api level 7 which doesn't support following method.
Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_MUSIC);
I have also tried following code :
path = Environment.getExternalStorageDirectory();
but I don't know how to specify path of music file.Please suggest some solution.Thanx.
Get path and song Name from SD Card. You can find the path of the song from MediaStore.
The Media provider contains meta data for all available media on both internal and external storage devices.
private String[] STAR = { "*" };
public void ListAllSongs()
{
Cursor cursor;
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
if (isSdPresent()) {
cursor = getContentResolver().query(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String songname = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
String albumname = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
public static boolean isSdPresent()
{
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
you can scan the entire sd card for any file format,here i used for mp3 and mp4.
you can use this for any format that u required.
/** To store the available media files */
private List<String> mediaList = new ArrayList<String>();
externalStoragePath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
targetDir = new File(externalStoragePath);
Log.d(" externalStoragePath ::: ", targetDir.getAbsolutePath());
public File[] mediaFiles = targetDir.listFiles();
/**
* scanFiles
*
* #param scanFiles
*/
public void scanFiles(File[] scanFiles) {
if (scanFiles != null) {
for (File file : scanFiles) {
if(mediaList.size() > 4){
return;
}
if (file.isDirectory()) {
// Log.d(" scaned File ::isDirectory: ",
// file.getAbsolutePath());
scanFiles(file.listFiles());
} else {
addToMediaList(file);
}
}
} else {
Log.d(SCANNER,
" *************** No file is available ***************");
}
}
/**
*
* #param file
*/
private void addToMediaList(File file) {
if (file != null) {
String path = file.getAbsolutePath();
int index = path.lastIndexOf(".");
String extn = path.substring(index + 1, path.length());
if (extn.equalsIgnoreCase("mp4") || extn.equalsIgnoreCase("mp3")) {// ||
Log.d(" scanned File ::: ", file.getAbsolutePath()
+ " file.getPath( ) " + file.getPath());// extn.equalsIgnoreCase("mp3"))
// {
Log.d(SCANNER, " ***** above file is added to list ");
mediaList.add(path);
}
}
}

Categories

Resources