Alireza
Alireza

Reputation: 71

How to obtain the folder name of a music file (or any file) dynamically

I have been searching on how to get the name of a folder (in internal sd card) containing my music files from the device but all the examples I saw was about how to get the file name not the folder. How can I write a code which is actually dynamic, meaning it does not matter what the file path is, it always gets the folder (directory) name of a file.

In my application I'm trying to get the folder name of my music files and save it as a string, using a cursor I did as follows

 ContentResolver musicResolver = getActivity().getContentResolver();
            Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

            if (musicCursor != null && musicCursor.moveToFirst()) {
                int pathColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA);


                counter = 0;
                do {
                    String thisPath = musicCursor.getString(pathColumn);
                    //String folderName = ???

                } while (musicCursor.moveToNext());

So this gives me the path which is something like this: /storage/emulated/0/folderName/fileName.ext

I would be thankful if someone could tell me how to get the folderName. Cheers.

Upvotes: 3

Views: 881

Answers (2)

Emanuel
Emanuel

Reputation: 8106

Parse it as file.

File f = new File(thisPath);
f.getParent();

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240860

create new File(thisPath) and invoke getParent() and call getName() on it

Upvotes: 4

Related Questions