I'm trying to make an app that can take images from a directory on the android phone and display them in a layout. I seem to be working my way towards a solution in a backwards manner. I know to use view.setBackgroundDrawable(Drawable.createFromPath(String pathName)); to display the image, but I don't know how to get the image's path from the directory.
I have a vague idea of what to do, but would appreciate clarification on this matter. I think the next step is to use:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
File file[] = Environment.getExternalStorageDirectory().listFiles();
}
But how do I filter the files so that only image files get stored in my file[]? Such as .png or .jpg/.jpeg files? And after that, should I use files[].getPath or files[].getAbsolutePath? I would store the result in a String[].
What I am mainly asking for is verification that the above code should work. And also, how I might filter to store only image files such as .png, .jpg and .jpeg.
Thank you for your time.
You want to do something like this for filtering:
File[] file = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
return filename.contains(".png");
}
});
If you want the filepath of the image of lets say the file at file[0], you would do this:
file[0].getAbsolutePath();
You want to implement a FileFilter and pass it to listFiles. You can create one that filters out only image files as you specified.
EDIT: and you want to use getAbsolutePath() as the argument to createFromPath.
Here is code for only to get .Png ,.jpg files and containing floders
private File[] listValidFiles(File file) {
return file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File file2 = new File(dir, filename);
return (filename.contains(".png") || filename.contains(".jpg") || file2
.isDirectory())
&& !file2.isHidden()
&& !filename.startsWith(".");
}
});
}
Related
Here I am trying to get pdf and csv files from WhatsApp Documents folder but not getting any instead of printing only Sent and Private folders only but I want all files from WhatsApp Documents
Please help
File srcFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/media/"+"com.whatsapp" + "/WhatsApp/Media/WhatsApp Documents/");
File[] allFiles = srcFile.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
System.out.println("filename="+filename);
return (filename.toLowerCase().endsWith(".pdf") && filename.toLowerCase().endsWith(".csv"));
}
});
list all files from WhatsApp Documents folder
Am am trying to work with this tutorial here which loads every image on the device into a grid view, but im not sure how to modify it to just display images from one particular directory in external storage.
Get the folder content with folder.listFiles() and create an Uri from every entry.
String folderName="Photos";
ArrayList<Uri> images = new ArrayList<Uri>();
File folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ folderName);
File[] files = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
return filename.endsWith(".jpg") || filename.endsWith(".png");
}
});
for (File file : files) {
images.add(Uri.parse(file.getAbsolutePath()));
}
Then you could use the array list with uris to pass it to the adapter.
I need to acces the sdcard and return some files of different formats. The location will be input by the user. How can I do this programmatically?
Simondid,
I believe this is what you are looking for.
Accessing the SDCard:
reading a specific file from sdcard in android
Keep in mind checking the media availability:
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
Creating a file filter:
http://www.devdaily.com/blog/post/java/how-implement-java-filefilter-list-files-directory
Example of a mp3 file filter, Create the following filter class:
import java.io.*;
/**
* A class that implements the Java FileFilter interface.
* It will filter and grab only mp3
*/
public class Mp3FileFilter implements FileFilter
{
private final String[] okFileExtensions =
new String[] {"mp3"};
public boolean accept(File file)
{
for (String extension : okFileExtensions)
{
if (file.getName().toLowerCase().endsWith(extension))
{
return true;
}
}
return false;
}
}
Then based on the earlier post of accessing the sdcard you would use the filter like this:
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard, "path/to/the/directory/with/mp3");
//THIS IS YOUR LIST OF MP3's
File[] mp3List = dir.listFiles(new Mp3FileFilter());
NOTE: The code is rough you probably want to make sure the sdcard is available as mentioned above
My program checks if a specific file exists in the default cache folder. If the file exists, it opens it and reads the contents. If the file does not exist, the file gets pulled from the web and is stored in the cache folder. The problem I'm having is that, no matter if the file is in the cache folder or not, my file test always returns false. The funny thing is that, even though the file test returns false, I can still open the file from the cache folder and read it. I can pull a list of files in the cache folder and I can see the file is there, but when I do the file test to see if the file is there, it returns false, even though I know the file is there and I can open it and see it's contents.
I tried the regular exists() test and even reading each file in the cache directory one by one and comparing the name to the file I'm looking for and still returns false.
Thanks for any help in advance!
String file = "test.txt"
String content = "testing";
putFile(file, content);
Boolean fileIsThere = checkFile(file);
public Boolean checkFile(String file){
Boolean fileExists = false;
// regular file test - always returns false, even if the file is there
File f = new File(file);
if (f.exists())
fileExists = true;
// comparing each individual file in the directory - also returns false
String[] dirFiles = fileList();
for (int i = 0; i < dirFiles.length; i++) {
if (dirFiles[i] == file){
fileExists = true;
break;
}
}
return fileExists;
}
public void putFile(String file, String content){
try {
FileOutputStream fos = openFileOutput(file, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
Log.w("putFile", "Error (" + e.toString() + ") with: " + file);
}
}
Any ideas? I'm thinking that since I'm putting the files in the cache folder, I will always get false on the file test. I just want to see if anyone else came across this and has a fix for it, or if I have to make a specific directory and store my files there, or something else. Could "Context.MODE_PRIVATE" in putFile() have anything to do with it?
If you want to test existention of file stored in your Context storage data/data/nameOfPackage/files/text.txt you have to rewrite String file like this
String file = "/data/data/nameOfPackage/files/test.txt"
Then you can check exists() method of your test.txt file. I hope it will help you. :)
if (f.exists() && f.length() > 0) fileExists = true;
This works for me!
I have an application that needs to read images from a folder created by the application on the sdcard(sdcard/"foldername"/"filename.jpg". I have no idea what the names of the files are because the user specifies the names of the files. I need to read the images from the folder and make something like the default image viewer. Im thinking read them into a grid view first but 1) cant figure out how to dynamically read them from a folder 2) how would I implement the image options like the default viewer? If there was a way to open the default viewer on a certain folder that would help.
any input would be amazing been working on it for a while.
Thanks
Here's how you can get a list of folders off of the memory card:
String state = Environment.getExternalStorageState();
if(state.contentEquals(Environment.MEDIA_MOUNTED) || state.contentEquals(Environment.MEDIA_MOUNTED_READ_ONLY))
{
String homeDir = Environment.getExternalStorageDirectory();
File file = new File(homeDir);
File[] directories = file.listFiles();
}
else
{
Log.v("Error", "External Storage Unaccessible: " + state);
}
This code is from the top of my head, so some syntax may be off a bit, but the general idea should work. You can use something like this to filter down the folders to only folders that contain images:
FileFilter filterForImageFolders = new FileFilter()
{
public boolean accept(File folder)
{
try
{
//Checking only directories, since we are checking for files within
//a directory
if(folder.isDirectory())
{
File[] listOfFiles = folder.listFiles();
if (listOfFiles == null) return false;
//For each file in the directory...
for (File file : listOfFiles)
{
//Check if the extension is one of the supported filetypes
//imageExtensions is a String[] containing image filetypes (e.g. "png")
for (String ext : imageExtensions)
{
if (file.getName().endsWith("." + ext)) return true;
}
}
}
return false;
}
catch (SecurityException e)
{
Log.v("debug", "Access Denied");
return false;
}
}
};
Then, change the first example to:
File[] directories = file.listFiles(filterForImageFolders);
That should return only directories that contain images. Hopefully this helps some!