I am trying to retrieve audio files from Private Folder for music player.
Below is my code -
public ArrayList<MusicFiles> getAllAudio(Context context){
SharedPreferences preferences = getSharedPreferences(MY_SORT_PREF, MODE_PRIVATE);
String sortOrder = preferences.getString("sorting", "sortByName");
ArrayList<String> duplicate = new ArrayList<>();
albums.clear();
ArrayList<MusicFiles> tempAudioList = new ArrayList<>();
String order = null;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
switch (sortOrder){
case "sortByName":
order = MediaStore.MediaColumns.DISPLAY_NAME + " ASC";
break;
case "sortByDate":
order = MediaStore.MediaColumns.DATE_ADDED + " ASC";
break;
case "sortBySize":
order = MediaStore.MediaColumns.SIZE + " DESC";
break;
}
String[] projection = {
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media._ID
};
String folder = getApplicationContext().getDir("Songs", MODE_PRIVATE).getAbsolutePath();
String selection = MediaStore.Audio.Media.DATA + " LIKE ? AND " + MediaStore.Audio.Media.DATA + " NOT LIKE ? ";
String[] selectionArgs = new String[]{
"%" + folder + "%",
"%" + folder + "/%/%"
};
Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, order);
if(cursor != null){
while(cursor.moveToNext()){
String album = cursor.getString(0);
String title = cursor.getString(1);
String duration = cursor.getString(2);
String path = cursor.getString(3);
String artist = cursor.getString(4);
String id = cursor.getString(5);
MusicFiles musicFiles = new MusicFiles(path, title, artist, album, duration, id);
//for checking
Log.e("Path: " + path, "Album : " + album);
tempAudioList.add(musicFiles);
if(!duplicate.contains(album)){
albums.add(musicFiles);
duplicate.add(album);
}
}
cursor.close();
}
return tempAudioList;
}
MediaStore
has no rights to access internal storage for apps, and so MediaStore
will not index them.
You can use ordinary filesystem APIs (e.g., listFiles()
on File
), to work with internal storage.
Note that you do not need getApplicationContext()
in your code snippet above.