MediaStore list all songs from specific path - android

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", "");
}

Related

Loading Artists from Android MediaStore along with Artwork

I am aware that media artwork is stored under albums and to get them you need to have the album id to access it. I have been able to get the images for tracks and albums using the album id.
However for artists table doesn't have the album id field. Other apps such as Play Music and Poweramp are somehow able to get the track artwork and add them to the respective artists.
How do i achieve this?
The way I do it is to get all albums for an artist and then use the rnd function to return an albumid:
String artist_id = c.getString(c.getColumnIndex(MediaStore.Audio.Artists._ID));
Cursor crs = album.getArtistsAlbumcursor(mContext, artist_id);
if(crs!=null && crs.moveToFirst()) {
Random rn = new Random();
int rnd = rn.nextInt( crs.getCount());
crs.moveToPosition(rnd);
album_id = crs.getLong(crs.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
crs.close();
}
where getArtistsAlbumcursor is:
public Cursor getArtistsAlbumcursor(Context context, String artistId) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String artistid = MediaStore.Audio.Media.ARTIST_ID;
final String[] columns = { _id, album_id, artistid };
String where = artistid +" =?";
String[] aId = {artistId};
return cr.query(uri, columns, where, aId, null);
}
Once you have an albumid you can get your albumart using your original method.
Or
if you want to get the albumart from the mp3 track itself, you will need to implement a libary such as jaudiotagger or org.blinkenlights.jid3.v2.
Life gets a little more complicated but below how to get albumart from the mp3 tag using the JID3 library:
try {
bmp = getmp3AlbumArt(sourceFile);
} catch (Exception e) {
e.printStackTrace();
}
where getmp3Albumart is:
public Bitmap getmp3AlbumArt(File SourceFile) throws Exception {
Bitmap bmp = null;
arrayByte = null;
APICID3V2Frame frames[];
MediaFile MediaFile = new MP3File(SourceFile);
try {
Object obj = null;
obj = MediaFile.getID3V2Tag();
if (obj != null) {
tagImage = (org.blinkenlights.jid3.v2.ID3V2_3_0Tag) obj;
if ((tagImage != null) && (arrayByte == null) && (tagImage.getAPICFrames() != null) && (tagImage.getAPICFrames().length > 0)) {
frames = tagImage.getAPICFrames();
for (int i = 0; i < tagImage.getAPICFrames().length; i++) {
if (frames[i] != null) {
arrayByte = frames[i].getPictureData();
break;
}
}
}
}
} catch (ID3Exception | OutOfMemoryError e) {
e.printStackTrace();
}
if (arrayByte != null) {
try {
bmp = BitmapFactory.decodeByteArray(arrayByte, 0, arrayByte.length);
} catch (Exception|OutOfMemoryError e) {
e.printStackTrace();
}
}
return bmp;
}

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

How to list audio files from Media Player and then play them in android

I want to get the list of all the songs that are added in the media player in android.
if i dont have a path to where all the music files are stored,then how can i retrieve the list of the songs?
is there any way to get the path where the songs are stored without taking the path from the user?
UPDATED->> i got the list. now i want to play the selected song from another activity when i am just passing the song name. is that possible? and how??
Please help.
Thanks
try below code to get mp3 from SDCard :-
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);
}
}
or
final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
final String[] cursor_cols = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
};
final String where = MediaStore.Audio.Media.IS_MUSIC + "=1";
final Cursor cursor = getContentResolver().query(uri, cursor_cols, where, null, null);
cursor.moveToNext();
final String artist = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
final String album = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
final String track = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
doSomethingHere(artist, album, track);

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();
}

android Reading all the Directories in SDCARD which has images

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());
}
}
}
}
}

Categories

Resources