android Reading all the Directories in SDCARD which has images - android

I am trying to read all the images in the SDCARD with the Directory in which its present. e.g: if there is a file TEST.jpg in /mnt/sdcard/album1 and TEST2.jpg in /mnt/sdcard/album1/album2 i should be able to get the directory name album1 and album2.
I have written a code which does this in recursive manner, This works when the no of folders are less but when the number of directories increases the loop just come out of it.
public void getImageFoldes(String filepath){
String albumpath;
File file = new File(filepath);
File[] files = file.listFiles();
for (int fileInList = 0; fileInList < files.length; fileInList++)
{
File filename;
filename =files[fileInList];
if(filename.isHidden()|| filename.toString().startsWith("."))
return;
if (filename.isDirectory()){
albumpath = filename.toString();
String[] split;
String title;
split= albumpath.split("/");
title=split[split.length-1];
result = new thumbnailResults();
result.setTitle(title);
result.setPath(albumpath);
result.setIsLocal(true);
//result.setCreated("05-06-2011");
getImageFoldes(filename.toString());
}
else{
if (files.length !=0)
{
//if File is the image file then store the album name
if ((files[fileInList].toString()).contains(".png")||
(files[fileInList].toString()).contains(".jpg")||
(files[fileInList].toString()).contains(".jpeg")){
if (!results.contains(result)){
result.setUri(Uri.parse(files[fileInList].getPath()));
results.add(result);
myadapter.notifyDataSetChanged();
}
}
}
}
}
}

Use the following code.
to get the path of all images and directories from sdcard.
public static ArrayList<String> getPathOfAllImages(Activity activity) {
ArrayList<String> absolutePathOfImageList = new ArrayList<String>();
String absolutePathOfImage = null;
String nameOfFile = null;
String absolutePathOfFileWithoutFileName = null;
Uri uri;
Cursor cursor;
int column_index;
int column_displayname;
int lastIndex;
// absolutePathOfImages.clear();
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaColumns.DATA,
MediaColumns.DISPLAY_NAME };
cursor = activity.managedQuery(uri, projection, null, null, null);
column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
column_displayname = cursor
.getColumnIndexOrThrow(MediaColumns.DISPLAY_NAME);
// cursor.moveToFirst();
while (cursor.moveToNext()) {
// for(int i=0; i<cursor.getColumnCount();i++){
// Log.i(TAG,cursor.getColumnName(i)+".....Data Present ...."+cursor.getString(i));
// }
// Log.i(TAG,"=====================================");
absolutePathOfImage = cursor.getString(column_index);
nameOfFile = cursor.getString(column_displayname);
lastIndex = absolutePathOfImage.lastIndexOf(nameOfFile);
lastIndex = lastIndex >= 0 ? lastIndex
: nameOfFile.length() - 1;
absolutePathOfFileWithoutFileName = absolutePathOfImage
.substring(0, lastIndex);
if (absolutePathOfImage != null) {
absolutePathOfImageList.add(absolutePathOfImage);
}
}
// Log.i(TAG,"........Detected images for Grid....."
// + absolutePathOfImageList);
return absolutePathOfImageList;
}

To get all the image files from the Sdcard, it may work.
public class ReadallImagesActivity extends Activity {
ArrayList<String> arlist = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File ff = Environment.getExternalStorageDirectory();
loadImagepaths(ff);
setContentView(R.layout.main);
Toast.makeText(ReadallImagesActivity.this, "Array size == " +arlist.size(), Toast.LENGTH_LONG).show();
}
public void loadImagepaths(File file) {
for (File f : file.listFiles()) {
if (f.isDirectory()) {
if (f.getAbsolutePath().endsWith(".android_secure")) {
break;
}
if (f.getAbsolutePath().endsWith("DCIM")) {
continue;
}
loadImagepaths(f);
} else {
if (f.getAbsolutePath().endsWith(".png") ||
f.getAbsolutePath().endsWith(".gif") ||
f.getAbsolutePath().endsWith(".jpg"))
{
arlist.add(f.getAbsolutePath());
}
}
}
}
}

Related

How to get images from hidden folder in android

I am able to fetch all the images from any specified non hidden folder from device but how can I get all the images from a hidden specified folder.
As soon as I mention my hidden folder name in the query, cursor return null
public static List<MediaData> getAppScannedImages(Context context) {
Cursor imagecursor = null;
List<MediaData> gallerydata = new ArrayList<MediaData>();
try {
final String orderBy = Images.ImageColumns.DATE_TAKEN + " DESC";
imagecursor = context.getContentResolver()
.query(Images.Media.EXTERNAL_CONTENT_URI,
projectionImage,
Images.Media.BUCKET_DISPLAY_NAME + "='"
+ ".myHiddenFolder" + "'", null,
orderBy);
if (imagecursor != null) {
imagecursor.moveToFirst();
int count = imagecursor.getCount();
for (int i = 0; i < count; i++) {
MediaData galData = new MediaData();
galData.setKey_id(i);
galData.setId(imagecursor.getString(0));
galData.setName(imagecursor.getString(1));
galData.setPath(imagecursor.getString(2));
galData.setDate(imagecursor.getString(3));
gallerydata.add(galData);
imagecursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (imagecursor != null) {
imagecursor.close();
}
}
return gallerydata;
}
You can try a different approach.
You have to find out the list of hidden folder from sd card and search all those folders for images.
the follwoing code is displays hidden files:
public void goTODir(File dir) {
//dir is initail dir like="/mnt/sdcard"
String imageType = ".jpg";
File[] listFile = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
goTODir(listFile[i]);
} else {
if (listFile[i].isHidden()){
if(listFile[i].getName().endsWith(imageType))
{
//add to your array list
}
}
}
}
}
}
String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path);
File listFile[] = dir.listFiles();
for (int i = 0; i < listFile.length; i++) {
if(listFile[i].getAbsolutePath().contains("your hidden folder name")){
File dirtest = new File(listFile[i].getAbsolutePath());
File listFiletest[] = dirtest.listFiles();
for (int j = 0; j < listFiletest.length; j++) {
get all images from hidden folder
}
}
}
For Kotlin Lover
companion object {
const val FOLDER_PATH = "/YourFolder/.hideen/"
}
/**
* Method to get all Image Path
* #return [ArrayList]
* */
fun getImagePath(): ArrayList<String> {
// image path list
val list: ArrayList<String> = ArrayList()
// fetching file path from storage
val file = File(Environment.getExternalStorageDirectory().toString() + FOLDER_PATH)
val listFile = file.listFiles()
if (listFile != null && listFile.isNullOrEmpty()) {
Arrays.sort(listFile, LastModifiedFileComparator.LASTMODIFIED_REVERSE)
}
if (listFile != null) {
for (imgFile in listFile) {
if (
imgFile.name.endsWith(".jpg")
|| imgFile.name.endsWith(".jpeg")
|| imgFile.name.endsWith(".png")
) {
val model : String = imgFile.absolutePath
list.add(model)
}
}
}
// return imgPath List
return list
}

How can i get list of all directory from SDcard in android? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to get folder from SDcard which have multiple images.
I have done to get all folder but i want to get folder which have images.
Here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.domore.folderlist.MainActivity">
<!--<ListView-->
<!--android:id="#+id/listview"-->
<!--android:layout_width="fill_parent"-->
<!--android:layout_height="wrap_content">-->
<!--</ListView>-->
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:numColumns="2"
android:stretchMode="columnWidth" >
</GridView>
</LinearLayout>
Here, is my MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private File file;
private List<String> myList;
private ArrayAdapter adapter;
GridView listview;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
File temp_file=new File(file,myList.get(position));
if(!temp_file.isFile()) {
file = new File(file, myList.get(position));
Log.e("CLICK PATH",""+file);
File list[] = file.listFiles();
myList.clear();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
//adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, myList);
listview.setAdapter(adapter);
// listview.setAdapter(new ImageAdapter(this,myList));
}
}
#Override
public void onBackPressed() {
// super.onBackPressed();
String parent = file.getParent().toString();
Log.e("PATH",parent);
file = new File(parent) ;
File list[] = file.listFiles();
myList.clear();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
// listview.setAdapter(new ImageAdapter(this,myList));
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,myList);
listview.setAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(GridView)findViewById(R.id.gridview);
myList=new ArrayList<String>();
String root_sd= Environment.getExternalStorageDirectory().getPath().toString();
Log.e("PATH",""+root_sd);
file=new File(root_sd);
File list[]=file.listFiles();
for(int i=0;i<list.length;i++){
myList.add(list[i].getName());
}
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,myList);
listview.setAdapter(adapter);
// listview.setAdapter(new ImageAdapter(this,myList));
listview.setOnItemClickListener(this);
}
}
Please, help me to solve out
in my application i write this code for load all photos:
Resolver = getContentResolver();
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
String[] directories = null;
if (u != null) {
c = managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst())) {
do {
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try {
dirList.add(tempDir);
} catch (Exception e) {
e.printStackTrace();
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for (int i = 0; i < dirList.size(); i++) {
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if (imageList == null)
continue;
for (File imagePath : imageList) {
try {
if (imagePath.isDirectory()) {
imageList = imagePath.listFiles();
}
if (imagePath.getName().toLowerCase(Locale.US).endsWith(".jpg")
|| imagePath.getName().toLowerCase(Locale.US).endsWith(".jpeg")
|| imagePath.getName().toLowerCase(Locale.US).endsWith(".png")) {
String path = imagePath.getAbsolutePath();
PhotosList.add(path);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try this
public void searchImageFromSpecificDirectory() {
String path = null;
String uri = MediaStore.Images.Media.DATA;
// if GetImageFromThisDirectory is the name of the directory from which image will be retrieved
String condition = uri + " like '%/GetImageFromThisDirectory/%'";
String[] projection = { uri, MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.SIZE };
Vector additionalFiles = null;
try {
if (additionalFiles == null) {
additionalFiles = new Vector<String>();
}
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
condition, null, null);
if (cursor != null) {
boolean isDataPresent = cursor.moveToFirst();
if (isDataPresent) {
do {
path = cursor.getString(cursor.getColumnIndex(uri));
System.out.println("...path..."+path);
additionalFiles.add(path);
}while(cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try these lines of code:-
File[] file = Environment.getExternalStorageDirectory().listFiles();
for (File f : file)
{
if (f.isDirectory()) {
file[] innerFiles = f.listFiles();
for(int i=0; i< innerFiles.length;i++){
Log.i("Name", innerFiles[i].getPath() + "");
///here you make the check that FOLDER consits IMAGE ofr NOT
if( innerFiles[i].getPath().contains(".JPG") || innerFiles[i].getPath().contains(".jpg"))
{
// YOU CAN PERFORM YOURS OPERATION HERE
}
}
}
if (f.isFile()) { ... do stuff }
}
if (f.isFile()) { ... do stuff }
}

Displaying folders only containing files with certain file type

I have set up code to display all folders that are on the SD card but now I am trying to figure out how to only display folders which contain MP3 files.
How can I filter out the folders that don't contain .MP3 files? thanks.
class:
public class FragmentFolders extends ListFragment {
private File file;
private List<String> myList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, myList));
}
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
File temp_file = new File(file, myList.get(position));
if (!temp_file.isFile()) {
file = new File(file, myList.get(position));
File list[] = file.listFiles();
myList.clear();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
Toast.makeText(getActivity(), file.toString(), Toast.LENGTH_LONG)
.show();
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, myList));
}
return;
}
}
You can check if the files within a directory are mp3 files before adding to your list view's dataset
Modify your code as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File(root_sd);
//list content of root sd
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
//check the contents of each folder before adding to list
File mFile = new File(file, list[i].getName());
File dirList[] = mFile.listFiles();
if(dirList == null) continue;
for (int j = 0; j < dirList.length; j++) {
if(dirList[j].getName().toLowerCase(Locale.getDefault()).endsWith(".mp3")){
myList.add(list[i].getName());
break;
}
}
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList));
}
I tested this and it works. Only caveat is, it doesn't check for sub-directories.
So in:
sdcard/Music/mistletoe.mp3
sdcard/Media/Tracks/mistletoe.mp3
only the Music folder will be listed.
Also, you may want to use an asyncTask to eschew hogging the UI thread
You can user a fileNameFilter and filter out the folders/files you don't want.
File baseDirectory = new File("/mnt/sdcard/"); //Your base dir here
File[] files = baseDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String fileName) {
File possibleMp3Folder = new File(dir, fileName);
if (possibleMp3Folder.isDirectory()) {
File[] files1 = possibleMp3Folder.listFiles();
for (File file : files1) {
if (file.getName().toLowerCase().endsWith(".mp3")) {
return true;
}
}
}
return false;
}
});
If you are looking for all folders contains mp3 files (both on Internal storage and SD Card) and available storages contains media:
Initialize two Sets for media storage paths and mp3 folders paths:
private HashSet<String> storageSet = new HashSet<>();
private HashSet<String> folderSet = new HashSet<>();
Get both in one method (you can return value if you need only one):
private void getMediaFolders() {
ContentResolver resolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = { MediaStore.Audio.Media.DATA };
Cursor cursor = resolver.query(uri, projection, selection, null, null);
if(cursor != null && cursor.getCount() > 0) {
int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
while(cursor.moveToNext()) {
String data = cursor.getString(dataIndex);
int i = 0;
for (int slashCount = 0; i < data.length(); i++) {
if (data.charAt(i) == '/' && ++slashCount == 3) {
storageSet.add(data.substring(0, i));
break;
}
}
if (data.toLowerCase().endsWith("mp3")) {
int lastSlashIndex = data.lastIndexOf('/');
while (i < lastSlashIndex) {
data = data.substring(0, lastSlashIndex);
folderSet.add(data);
lastSlashIndex = data.lastIndexOf('/');
}
}
}
}
if (cursor != null) { cursor.close(); }
}
Filter folders (with Annimonstream):
private ArrayList<File> getFilteredFolders(#NonNull String path, HashSet<String> folderSet) {
File[] filesList = new File(path).listFiles();
if (filesList == null) { return new ArrayList<>(); } // Or handle error as you wish
return Stream.of(filesList)
.filter(File::isDirectory)
.filter(f -> folderSet.contains(f.getAbsolutePath()))
.collect(Collectors.toCollection(ArrayList::new));
}
Show storages (if needed).
Uri,Projection,
MediaStore.Video.Media.DATA
+ " like " + "'%.mp4%'"
+ " AND "
+ MediaStore.Video.Media.DATA
+ " like " + "'%" + getResources().
getString(R.string.string_store_video_folder)
+"%'", null,
MediaStore.Video.Media.DATE_MODIFIED
this will give mp4 files in a specific folder

MediaStore list all songs from specific path

I want to get all the songs from one specific path on the device.
in a example i want to get all the songs from one specific folder "music" from path: "/mnt/sdcard/music/" , what i need to change in my code to able to achieve this?
i have this method that get all the songs from the device:
public ArrayList<Song> scanAllSongsOnDevice(Context c)
{
ContentResolver musicResolver = c.getContentResolver();
Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String col[] ={android.provider.MediaStore.Audio.Media._ID};
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst())
{
// clear list to prevent duplicates
songsList = new ArrayList<>();
//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);
int isMusicColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Media.IS_MUSIC);
int duration = musicCursor.getColumnIndex
(MediaStore.Audio.Media.DURATION);
//add songs to list
do
{
String filePath = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
// check if the file is a music and the type is supported
if (musicCursor.getInt(isMusicColumn) != 0 && filePath != null && (FileExtensionFilter.checkValidExtension(filePath)) && musicCursor.getInt(duration) > 0)
{
int thisId = musicCursor.getInt(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
Song song = new Song();
song.setId(thisId);
if(!thisArtist.equals("<unknown>"))
{
song.setArtist(thisArtist);
song.setTitle(thisTitle);
}
else
{
song.setArtist("");
song.setTitle("");
}
song.setSongPath(filePath);
File file = new File(filePath);
song.setFileName(file.getName().substring(0, (file.getName().length() - 4)));
songsList.add(song);
}
}
while (musicCursor.moveToNext());
}
else // if we don't have any media in the folder that we selected set NO MEDIA
{
addNoSongs();
}
musicCursor.close();
if(songsList.size() == 0)
{
addNoSongs();
}
Collections.sort(songsList, new Comparator<Song>()
{
#Override
public int compare(Song song, Song song2)
{
int compare = song.getTitle().compareTo(song2.getTitle());
return ((compare == 0) ? song.getArtist().compareTo(
song2.getArtist()) : compare);
}
});
return songsList;
}
You need to modify your audioCursor like
audioCursor = audioResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,MediaStore.Audio.Media.DATA + " like ? ",
new String[] {"%YOUR_SPECIFIC_FOLDER_NAME%"}, null);
Hope it will help you...
Thanks
Firstly you need to add the data of you songs to system's media store by MediaScanner.
String scanDir = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
scanDir = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "music";
} else {
// sdcard is not available
}
MediaScannerConnection.scanFile(getApplicationContext(),
new String[] { scanDir },
new String[] { "audio/*" },
new OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
This will send a broadcast intent to framework, the framework will scan the directory you specify and add the scanned result to system media store database.
After that, you can access the data by contentresolver like the code you pasted.
Change your filePath variable to this:
String filePath = Environment.getExternalStorageDirectory() + "/music";
public ArrayList<File> findSong(File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles(); // All file and folder automatic collect
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSong(singleFile)); //Recursively call
} else {
if (singleFile.getName().endsWith(".mp3")) {
al.add(singleFile);
}
}
}
return al;
}
onCreate:
final ArrayList<File> mySongs = findSong(Environment.getExternalStorageDirectory());
items = new String[mySongs.size()];
for (int i = 0; i < mySongs.size(); i++) {
// toast(mySongs.get(i).getName().toString());
// items[i] = mySongs.get(i).getName().toString();
items[i] = mySongs.get(i).getName().toString().replace(".mp3", "");
}

How to find mp3 files from sdcard in android programatically

I am new to android programming so can anyone please help me to find all .mp3 files in my android device.
You should use MediaStore. Here is an example code i'm using for something similar:
private static ArrayList<SongModel> LoadSongsFromCard() {
ArrayList<SongModel> songs = new ArrayList<SongModel>();
// Filter only mp3s, only those marked by the MediaStore to be music and longer than 1 minute
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
+ " AND " + MediaStore.Audio.Media.MIME_TYPE + "= 'audio/mpeg'"
+ " AND " + MediaStore.Audio.Media.DURATION + " > 60000";
final String[] projection = new String[] {
MediaStore.Audio.Media._ID, //0
MediaStore.Audio.Media.TITLE, //1
MediaStore.Audio.Media.ARTIST, //2
MediaStore.Audio.Media.DATA, //3
MediaStore.Audio.Media.DISPLAY_NAME
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
Cursor cursor = null;
try {
// the uri of the table that we want to query
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; //getContentUriForPath("");
// query the db
cursor = _context.getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//if (cursor.getString(3).contains("AwesomePlaylists")) {
SongModel GSC = new SongModel();
GSC.ID = cursor.getLong(0);
GSC.songTitle = cursor.getString(1);
GSC.songArtist = cursor.getString(2);
GSC.path = cursor.getString(3);
// This code assumes genre is stored in the first letter of the song file name
String genreCodeString = cursor.getString(4).substring(0, 1);
if (!genreCodeString.isEmpty()) {
try {
GSC.genre = Short.parseShort(genreCodeString);
} catch (NumberFormatException ex) {
Random r = new Random();
GSC.genre = (short) r.nextInt(4);
} finally {
songs.add(GSC);
}
}
//}
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
return songs;
}
Of course . you can . Code not tested.
File dir =new File(Environment.getExternalStorageDirectory());
if (dir.exists()&&dir.isDirectory()){
File[] files=dir.listFiles(new FilenameFilter(){
#Override
public boolean accept(File dir,String name){
return name.contains(".mp3");
}
});
}
You can use recursive searching. Use this function with path of directory where you wanna start search .mp3 files (for example "/mnt/sdcard").
public Vector<String> mp3Files = new Vector<String>();
private void searchInDirectory(String directory)
{
File dir = new File(directory);
if(dir.canRead() && dir.exists() && dir.isDirectory())
{
String []filesInDirectory = dir.list();
if(filesInDirectory != null)
{
for(int i=0; i<filesInDirectory.length; i++)
{
File file = new File(directory+"/"+filesInDirectory[i]);
if(file.isFile() && file.getAbsolutePath().toLowerCase(Locale.getDefault()).endsWith(".mp3"))
{
mp3Files.add(directory+"/"+filesInDirectory[i]);
}
else if(file.isDirectory() )
{
searchInDirectory(file.getAbsolutePath());
}
}
}
}
}
public ArrayList<String> searchMP3File(ArrayList<String> aListFilePath, String rootPath) {
File rootFile = new File(rootPath);
File[] aRootFileFilter = rootFile.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
if(pathname.getName().endsWith(".mp3"))
return true;
else
return false;
}
});
if(aRootFileFilter != null && aRootFileFilter.length > 0) {
for(int i = 0; i < aRootFileFilter.length; i++) {
aListFilePath.add(aRootFileFilter[i].getPath());
}
}
File[] aRootFile = rootFile.listFiles();
for(int i = 0; i < aRootFile.length; i++) {
if(aRootFile[i].isDirectory()) {
ArrayList<String> aListSubFile = searchMP3File(aListFilePath, aRootFile[i].getPath());
if(aListSubFile != null && aListSubFile.size() > 0)
aListFilePath = aListSubFile;
}
}
return aListFilePath;
}
private String[] videoExtensions;
videoExtensions = new String[2];
videoExtensions[0] = "mp3";
videoExtensions[1] = "3gp";
After this declaration in your onCreate() method, set below code in some method and call it. Do changes as per your need in my code.
try {
File file = new File("mnt/sdcard/DCIM/Camera");
File[] listOfFiles = file.listFiles();
videoArray = new ArrayList<HashMap<String, String>>();
videoHashmap = new HashMap<String, String>();
for (int i = videoIndex; i < listOfFiles.length; i++) {
File files = listOfFiles[i];
rowDataVideos = new HashMap<String, String>();
for (String ext : videoExtensions) {
if (files.getName().endsWith("." + ext)) {
videoHashmap.put("Video", files.getAbsolutePath());
videoArray.add(videoHashmap);
fileSize = files.length();
fileSizeInMb += convertSize(fileSize, MB);
thumb = ThumbnailUtils.createVideoThumbnail(files.getAbsolutePath(), MediaStore.Images.Thumbnails.MINI_KIND);
if (thumb != null) {
createTempDirectory();
try {
FileOutputStream out = new FileOutputStream(audiofile);
thumb.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Tue Apr 23 16:08:28 GMT+05:30 2013
lastModDate = new Date(files.lastModified()).toString();
dateTime = (dateToMilliSeconds(lastModDate) / 1000L);
rowDataVideos.put(VIDEOPATH, files.getAbsolutePath());
rowDataVideos.put(VIDEOSTATUS, "0");
rowDataVideos.put(VIDEOSIZEINMB, String.valueOf(fileSizeInMb));
rowDataVideos.put(VIDEODATE, String.valueOf(dateTime));
if (dateTime > (RESPONSE_TIMESTAMP_VIDEO / 1000L)) {
dataProvider.InsertRow(VIDEOS, rowDataVideos);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources