Android: Retrieve all image directories - android

I am trying to find all directories on an Android device that contain images (internal as well as external storage).
Basically, I try to get all the directories that are listed in the native gallery application
So for example:
All images
Downloads
My Favourites
Whatsapp Pictures
...
How does one accomplish this? I think it is related to MediaStorage.Images.Media and so on, but the documentation is not very helpful there and a lot of google searches didn't help as well.

Thanks to #BlazingFire, who did not fully answer my question, but provided some code I could work with and have now my desired result:
public ArrayList<String> getFile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (File file : listFile) {
if (file.isDirectory()) {
getFile(file);
}
else {
if (file.getName().endsWith(".png")
|| file.getName().endsWith(".jpg")
|| file.getName().endsWith(".jpeg")
|| file.getName().endsWith(".gif")
|| file.getName().endsWith(".bmp")
|| file.getName().endsWith(".webp"))
{
String temp = file.getPath().substring(0, file.getPath().lastIndexOf('/'));
if (!fileList.contains(temp))
fileList.add(temp);
}
}
}
}
return fileList;
}
It only adds parent directories of images and only if they have not yet been added. I also included .bmp and .webp as valid image file extensions

You can use this code to find picture folders in Storage -
private ArrayList<File> fileList = new ArrayList<File>();
...
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif"))
{
String temp = file.getPath().substring(0, file.getPath().lastIndexOf('/'));
fileList.add(temp);
}
}
}
return fileList;
}
And then you can call the ArrayList this way -
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
getFile(root);
for (int i = 0; i < fileList.size(); i++) {
String stringFile = fileList.get(i).getName();
Do whatever you want to do with each filename here...
}

Related

list the files from internal storage android

I am currently working with internal storage
i have some problems,
I am also get the files in particular folder on internal storage,but my list shows all root folders like data/data/com.example.app/sample.mp4, But i want only filename like sample.mp4.
Here my code
`
ArrayList<File> fileList = new ArrayList<File>();
File mydir = this.getDir("Myfolder", Context.MODE_PRIVATE);
File listFile[] = mydir.listFiles();
if (listFile != null && listFile.length > 0) {
for (File aListFile : listFile) {
if (aListFile.isDirectory()) {
fileList.add(aListFile);
} else {
if (aListFile.isFile());
{
fileList.add(aListFile);
}
}
}`
Get filename from file object
if (aListFile.isFile());
{
string fileName = aListFile.getName();
}
try this one,
YourFilePath.substring(YourFilePath.lastIndexOf("/")+1)
For example,
String filePath = "data/data/com.example.app/sample.mp4"
String fileName = filePath.subString(filePath.lastIndexOf("/")+1);
And finally you get your fileName = sample.mp4

Delete files from a known folder

I'm trying to delete all files that are exists in a known path.
I've used the next function to do so -
public void deleteAllImages(){
Log.d(TAG, "ENTERD DELETED ALL IMAGES ");
String path = "/data/data/yourapp/app_data/imageDir/";
File directory = new File(path);
if (directory.isDirectory()){
Log.d(TAG, "ENTERED IF ");
for (File child : directory.listFiles()){
Log.d(TAG, "ENTERED FOR "+ child);
child.delete();
}
}
}
But it seem that it never getting into the if statement - guess it mean that it doesn't treat directory as one. So what am I doing wrong here?
Most likely the path is not correct. The isDirectory() will return false in the following cases:
The path points to file (obviously), and not to directory.
The path
is invalid (i.e. there is no such file/directory exists).
There is
not enough permissions granted to your application to determine
whether path points to directory.
Try this :
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).delete();
}
}
Check this : Delete files from folder
Hope this helps.
try this...
String path = "/data/data/yourapp/app_data/imageDir/";
File file = new File(path);
if(file.isDirectory()) {
File[] files = file.listFiles();
if(files != null && files.length > 0) {
for (File file2 : files) {
file2.delete();
}
}
}

how to create only deleted file instead of creating entire level under directory of sdcard in android

In sdcard of android device there is a directory with 3 levels of files each with different count of files, i can list all of them using
public void listDirectory(String dirPath, int level) {
File dir = new File(dirPath);
File[] firstLevelFiles = dir.listFiles();
if (firstLevelFiles != null && firstLevelFiles.length > 0) {
for (File aFile : firstLevelFiles) {
for (int i = 0; i < level; i++) {
System.out.print("\t");
}
if (aFile.isDirectory()) {
System.out.println("[" + aFile.getName() + "]");
listDirectory(aFile.getAbsolutePath(), level + 1);
} else {
System.out.println(aFile.getName());
}
}
}
}
but i any file is deleted, i should create only deleted file, without disturbing the file structure.

How to Filter .txt file from the sdcard

I want to list of the Text file in Listview and Select .txt file path get from the sdcard.
Try this :
public void scandir(File dir) {
String txtPattern = ".txt";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
scandir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(txtPattern)){
//Do what ever u want
}
}
}
}
}
Make a call like this:
scandir(Environment.getExternalStorageDirectory());
Reference :
Android List documents with Specific extension from SD Card
Use .endsWith() method from Java String Class to check File Extension from file path.
you can see my answer here
(another option)
You can use FilenameFilter Interface to Shortlist all TextFiles are any related files to an Array. check this answer here to shortlist only image files from SD card.

android list all folders that has an image

As part of my app i need to have file browser that lists only specific folders.
For eg list only those folders in the path that an image file in any of its subfolders in any level.
I could do it using recursion. But it affects performance. Especially finding folders at top level need many recursive calls. Is there a better way to do it
Please see my code below
public List<GeneralFileItem> getGridItemsList(String root) {
List<GeneralFileItem> gridItemsList = new ArrayList<GeneralFileItem>();
File file;
file = new File(root);
File list[] = file.listFiles();
if (list.length == 0) {
return null;
}
for (int i = 0; i < list.length; i++) {
GeneralFileItem item = new GeneralFileItem();
File temp_file = new File(file.getAbsolutePath(), list[i].getName());
if (hasPhoto(temp_file)) {
item.setPath(file.getAbsolutePath() + "/" + list[i].getName());
item.setName(list[i].getName());
if (temp_file.listFiles() != null) {
item.setType(GeneralFileItem.DIRECTORY_TYPE);
} else {
item.setType(GeneralFileItem.FILE_TYPE);
}
gridItemsList.add(item);
//Log.i(TAG,"added"+list[i].getName());
}
}
return gridItemsList;
}
private boolean hasPhoto(File temp_file) {
//Log.i(TAG,temp_file.getName());
if (temp_file.listFiles() == null) {
if (temp_file.getName().toUpperCase().endsWith(("JPG"))) {
//Log.i(TAG,temp_file.getName()+ "is a photo");
return true;
} else
return false;
}
else{
File list[] = temp_file.listFiles();
for (int i = 0; i < list.length; i++) {
if(hasPhoto(list[i]))
return true;
}
}
return false;
}
I want to know if there is any other way than recursive search. How are the files maintained in Android. I know that various file systems are supported and it varies from hardware manufaturer . I would like to know if there is a way like if there is FileTable from which i can get all .jpg files .
use FilenameFilter to search for specirfic type of files.
presently you are checking only current directory.However if you wish to search recursively then you will have to check if each file found is a directory or not
Your algo would be something like
File file;
file = new File(root);
File list[] = file.listFiles();
if (list.length == 0) {
return null;
}
for (int i = 0; i < list.length; i++) {
if(list[i].isDirectory()){
//Then go inside it to search for specific file
File subList[] = list[i].listFiles();
//search for jpg..
}else if("is this jpg"){
//Add to list
}
}
To simplify this you could segregate these into methods as per your requirement.
Here's something I came up! It works like a charm!
First you must create a File, this one is root of SD card
File = rootPrimary = new File(Environment.getExternalStorageDirectory());
than you must list all the files in to a File []
File[] fileArray = rootDirectory.listFiles();
Then you create a ArrayList and set it equal to a method i've created and pass the File[] in.
ArrayList<File> alFolders = new ArrayList<File>();
alFolder = putImgFldr(fileArray);
This method will add all dorectoryes that contain images with .jpg and .png extension.
private ArrayList<File> putImgFldr(File[] fileArray) {
// TODO Auto-generated method stub
ArrayList<File> a = new ArrayList<File>();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isDirectory()) {
//if file is folder pass that file trough this method
a.addAll(putImgFldr(fileArray[i].listFiles()));
} else if (fileArray[i].getAbsolutePath().endsWith(".jpg") || fileArray[i].getAbsolutePath().endsWith(".png")) {
// if file is img ad it's parent, folder to ArrayList
a.add(fileArray[i].getParentFile());
// this finishes the file searching
// because the image has allready bean found
i = fileArray.length + 1;
}
}
return a;
}
now You can add another File [] to alFolders if nessesery
alFolders.addAll(putImgFldr(secFileArray));
One more example of listing files and directories using Java 8 filter. For instance, here I am using just jpeg images
public static void main(String[] args) {
System.out.println("Files!!");
try {
Files.walk(Paths.get("."))
.filter(Files::isRegularFile)
.filter(c ->
c.getFileName().toString().substring(c.getFileName().toString().length()-4).contains(".jpg")
||
c.getFileName().toString().substring(c.getFileName().toString().length()-5).contains(".jpeg")
)
.forEach(System.out::println);
} catch (IOException e) {
System.out.println("No jpeg or jpg files");
}
System.out.println("\nDirectories!!\n");
try {
Files.walk(Paths.get("."))
.filter(Files::isDirectory)
.forEach(System.out::println);
} catch (IOException e) {
System.out.println("No Jpeg files");
}
}

Categories

Resources