Fetch all songs from specific path - android

I am trying to fetch all songs from a specific folder. Currently, I am fetching all songs and then on basis of path I am looping and getting songs in the specific path.Any better way to do this?
for (int i = 0; i < totalSongList.size(); i++) {
String path = totalSongList.get(i).getPathId();
int index = path.lastIndexOf("/");
String folderPath1 = path.substring(0, index);
if (folderPath.equals(folderPath1))
songList.add(totalSongList.get(i));
}
I can't use below code also as it will fetch sub folder songs also.
musicResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,MediaStore.Audio.Media.DATA + " like ? ",
new String[] {"%SPECIFIC_FOLDER_NAME%"}, null);

Here is java code without using mediaStore for retrieving all songs from the specific folder which may or maynot contain any subfolder.
public String File path = new File("your folder path here");
public void Search(File dir)
{
if(dir.isFile())
{
//get necessary songName over here
String songName = dir.getName();
//if you need path
String songPath = dir.getAbsolutePath();
//if your folder consists of other files other than audio you have to filer it
if(songName.endsWith(".mp3") || songName.endsWith(".MP3")
{
//this is the required mp3 files
//do what you want to do with it
}
}else if(dir.isDirectory())
{
File[] list = dir.listFiles();
for(int i=0;i<list.length();i++)
{
search(list[i]);
}
}
else
{
//handle exceptions here
}
}

Related

How to check pdf files from mobile storage and list the name by consensus with dynamic list view

I have dynamic listView linked with JSONArray, in the adapter i'm trying to read the storage to check if the pdf file is downloaded already the Button text will be View and will call View method but if the the file not there the Button text will be Download and will call Download method.
I have been trying this code but it's not work
String path2 = Environment.getExternalStorageDirectory() + "/materialpdffolder/";
File path = new File(path2);
File list[] = path.listFiles();
for( int i=0; i < materialList.size() ; i++)
{
for( int x=0; x <= list.length ; x++) {
if (list[x].getName() != null) {
if (list[x].getName().equals(materialList.get(position).getMaterial_file_name().toString())) {
DVmaterial.setText("View(" + materialList.get(position).getMaterial_file_name().toString() +")" );
}}else
{
DVmaterial.setText("Download(" + materialList.get(position).getMaterial_file_name().toString() + ")");
}
}
}
The problem is when there’s no file, the application is stack and give error and not give any results for list[x].get Name() and when I use materiallist.size() for for looping it is doesn’tgive a correct answer
Try to change with this code
if (list[x].getName() != null) {
if (list[x].getName().equals(materialList.get(position).getMaterial_file_name().toString())) {
DVmaterial.setText("View(" + materialList.get(position).getMaterial_file_name().toString() +")" );
}else
{
DVmaterial.setText("Download(" + materialList.get(position).getMaterial_file_name().toString() + ")");
}
}
Remove one bracket from }}else and put it end of else

Get all folders with photo - Android

String albumName = albumTitle;
String ExternalStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/My_Albums/" + albumName;
File targetDirectory = new File(ExternalStorageDirectory);
if (targetDirectory != null) {
File[] files = targetDirectory.listFiles();
if (files != null) {
filePathString = new String[files.length];
fileNameString = new String[files.length];
for (int i = 0; i < files.length; i++) {
filePathString[i] = files[i].getAbsolutePath();
System.out.println("filePAthStr: " + filePathString[i]);
fileNameString[i] = files[i].getName();
System.out.println("fileNameStr: " + fileNameString[i]);
customGridAdapter.add(filePathString[i]);
}
}
}
How do I get all folders with photo.
How do I get media from mediastore efficiently
Intially , album name will be empty
String albumName = albumTitle;
So if you aint enter the album name, the path would be like
String ExternalStorageDirectory = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/My_Albums/";
it will go the parent path ,get all the albums under that node and display the number of images under it.
when once you provide albumname,it will get all images inside it and displays.In this scenario you need to loop inside album to cover each and every album under it and get the image paths from them.
UPDATE
For implementing this Logic refer link : Get All Folders With Photos
I got the solution, which was quite simple.
if(albumName != null && !albumName.equals("")){
// Only then set the adapter
}

Get a list of filenames in a drawable resource directory

I want to get a list of certain filenames in a drawable resource directory (at runtime, not using XML). I guess, I would need to distinguish certain files from others. So ...
*res/drawable-hdpi/mysubdir
-- x-one.png
-- one.png
-- x-two.png
-- two.png
-- x-three.png
-- three.png
*
I want to put the x-*.png filenames into a List<String>. Is this possible?
Borrowing some code from another question, I can get all the drawables, but I don't see a way to distinguish one from another in a meaningful way.
private void getDrawableResources() {
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> drawableClass = R.drawable.class;
final Field[] fields = drawableClass.getDeclaredFields();
final List<Integer> resourceIdList = new ArrayList<Integer>();
for (int i = 0, max = fields.length; i < max; i++) {
final int resourceId;
try {
resourceId = fields[i].getInt(drawableResources);
resourceIdList.add(resourceId);
}
catch (Exception e) {
continue;
}
}
Resources resources = this.getActivity().getResources();
for (int i = 0; i < resourceIdList.size(); i++) {
Drawable drawable = resources.getDrawable(resourceIdList.get(i));
resourceIdList.get(i) + "): " + drawable.toString());
}
}
Resource directories do not support subdirectories.
Use FileNameFilter while getting list of files in a directory.
File dir = new File(dirLocation);
if(dir.exists() && dir.isDirectory())
{
File[] files = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.contains("X-");
}
});
}

Get files and directory listings in android

I am working on an android project and I am trying to get a list of files and directories from the SD Card. It seems to be more a less working except the file name is outputting a load of nonsense and I can't see why.
Below is the code I am using to get the file listing.
public ArrayList getFileDirectoryListing()
{
ArrayList fileAndDirectories = new ArrayList();
final String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File[] files = Environment.getExternalStorageDirectory().listFiles();
for (int i = 0; i < files.length; i++)
{
FileDirectoryDetails fileDirectoryDetails = new FileDirectoryDetails();
fileDirectoryDetails.path = files[i].getName();
if (files[i].isDirectory())
{
fileDirectoryDetails.fileOrDirectory = FileOrDirectory.Directory;
}
else
{
fileDirectoryDetails.fileOrDirectory = FileOrDirectory.File;
}
fileAndDirectories.add(fileDirectoryDetails);
}
}
return fileAndDirectories;
}
Below is the code I am using to set the list adapter
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
listView = getListView();
ArrayList<FileDirectoryDetails> filesAndDirectories = getFileDirectoryListing();
fileDirectoryDetailsArrayAdapter = new
ArrayAdapter<FileDirectoryDetails>(this, android.R.layout.simple_list_item_1, filesAndDirectories);
setListAdapter(fileDirectoryDetailsArrayAdapter);
}
Below is a screenshot of what I am getting back in the list view instead of the actual file names.
Make sure you override toString() in your FileDirectoryDetails returning meaningful details. Currently you're using the default toString()
Or just fill your array with paths strings instead of the whole FileDirectoryDetails
Alternatively, override getView() of the adapter setting the text of the TextView to details.path

Android: Sorting mp3 files by title in a clickable listview

I am attempting to create a music player app for a Nexus 7 tablet. I am able to retrieve music files from a specific directory as well as information that is associated with them such as title, artist, etc. I have loaded the files's titles into a clickable list view. When the user clicks on a title, it takes them to an activity that plays the associated song. I was attempting to sort the titles alphabetically and ran into a snag. When I sort just the titles, they no longer match with the correct songs. This is to be expected since I only ordered the titles and not the actual files. I attempted to modify the sorting algorithm by doing this:
//will probably only work for Nexus 7
private final static File fileList = new File("/storage/emulated/0/Music/");
private final static File fileNames[] = fileList.listFiles(); //get list of files
public static void sortFiles()
{
int j;
boolean flag = true;
File temp;
MediaMetadataRetriever titleMMR = new MediaMetadataRetriever();
MediaMetadataRetriever titleMMR2 = new MediaMetadataRetriever();
while(flag)
{
flag = false;
for(j = 0; j < fileNames.length - 1; j++)
{
titleMMR.setDataSource(fileNames[j].toString());
titleMMR2.setDataSource(fileNames[j+1].toString());
if(titleMMR.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE).compareToIgnoreCase(titleMMR2.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)) > 0)
{
temp = fileNames[j];
fileNames[j] = fileNames[j+1]; // swapping
fileNames[j+1] = temp;
flag = true;
}//end if
}//end for
}//end while
}
This is supposed to retrieve the song titles from two files, compare them, and swap the files in the File array if the first comes after the second alphabetically. For some reason, when I run the activity that calls this method, the app crashes. If I remove the + 1 from titleMMR2's data source
titleMMR2.setDataSource(fileNames[j].toString());
the app no longer crashes but the list is not in order. Again this is understandable since it compares the song titles to themselves. I don't know why the + 1 would make the program crash. It is not an array out of bounds error. There are a total of 6 .mp3 files in the directory and they are the only files in that directory. I have also tried using Arrays.sort(fileNames) but that only orders them by their file name and not song title. I also tried this:
Arrays.sort(fileNames, new Comparator<File>(){
public int compare(File f1, File f2)
{
titleMMR.setDataSource(f1.toString());
titleMMR2.setDataSource(f2.toString());
return titleMMR.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE).compareToIgnoreCase(titleMMR2.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE));
} });
That snippet also resulted in a crash. There are no errors in the java code and all appropriate classes have been imported. I'm really at a loss as to what is wrong. Any help will be appreciated and if any new info is needed I will gladly provide it. Thanks in advance.
FIXED
The correct code snip is this:
public static void sortFiles()
{
int j;
boolean flag = true;
File temp;
MediaMetadataRetriever titleMMR = new MediaMetadataRetriever();
MediaMetadataRetriever titleMMR2 = new MediaMetadataRetriever();
while(flag)
{
flag = false;
for(j = 0; j < fileNames.length - 1; j++)
{
titleMMR.setDataSource(fileNames[j].toString());
titleMMR2.setDataSource(fileNames[j+1].toString());
String title1;
String title2;
if(titleMMR.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE) == null)
title1 = fileNames[j].getName();
else
title1 = titleMMR.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
if(titleMMR2.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE) == null)
title2 = fileNames[j+1].getName();
else
title2= titleMMR2.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
if(title1.compareToIgnoreCase(title2) > 0)
{
temp = fileNames[j];
fileNames[j] = fileNames[j+1]; // swapping
fileNames[j+1] = temp;
flag = true;
}//end if
}//end for
}//end while
}

Categories

Resources