Android: how to populate GridView from read SD Card Folder images? - android

I have a part of code which search my folders, which have images. Can somebody show me how to add them to GridView and how after using OnItemClickListener to show images in them?
public static List<File> findImageDirectories(File parentDirectory){
List<File> directories = new ArrayList<File>();
if (parentDirectory.listFiles() != null){
for (File file: parentDirectory.listFiles()){
// If the parentDirectory contains an image file
if (isImageFile(file)){
directories.add(parentDirectory);
break;
}
// If it contains a subfolder, check the subfolder as well
else if (file.isDirectory()){
findImageDirectories(file);
}
}
}
return directories;
private static boolean isImageFile(File f) {
String name = f.getName();
if (name.endsWith(".jpg") || name.endsWith(".png"))
// Add other formats as desired
{
return true;
}
return false;
}

Related

How to read file names of the files that are present in the android's Internal/External storage

I am trying to program my own file manager for android. What I want to know is that how can I read the file names of all the files present in external/internal storage?
I want to read the file names and show them in a listview so the user could see what files are present in what folder. I know this thing is going to work in recursive manner as I have to read the content of sub directories as well.
This is what you have to do. Before going to write please refer the File class in java. This will help you to clear lot of things.
Below is the snippet that provides the list of files.
File directory = new File(path);
File[] listFiles = directory.listFiles();
if (listFiles != null) {
for (File file : listFiles) {
if (file.isDirectory())
// do the stuff what you need
else if (file.isFile()) {
// do the stuff what you need
}
}
}
}
Following code will give you list of files in android sdcard:
/**
* Return list of files from path. <FileName, FilePath>
*
* #param path - The path to directory with images
* #return Files name and path all files in a directory, that have ext = "jpeg", "jpg","png", "bmp", "gif"
*/
private List<String> getListOfFiles(String path) {
File files = new File(path);
FileFilter filter = new FileFilter() {
private final List<String> exts = Arrays.asList("jpeg", "jpg",
"png", "bmp", "gif");
#Override
public boolean accept(File pathname) {
String ext;
String path = pathname.getPath();
ext = path.substring(path.lastIndexOf(".") + 1);
return exts.contains(ext);
}
};
final File [] filesFound = files.listFiles(filter);
List<String> list = new ArrayList<String>();
if (filesFound != null && filesFound.length > 0) {
for (File file : filesFound) {
list.add(file.getName());
}
}
return list;
}
You can call same method to get sub directory file also.

check if the image is in assets folder if image exists return its path in android

I have some images in assets folder.
Now i want a code to check if the image exists. And if image exits then it has to return its path.
So what can be the possible steps to find a path of images or text files in assets folder in android?
I used this method: but i want to get the path of images stored in assets folder.
public String filePath(String image) throws IOException{
String myfilepath = Environment.getExternalStorageDirectory().toString()+"/"+image;
return myfilepath;
}
public String filePath(String image,Context _context)
{
File file = new File(_context.getCacheDir()+File.separator+image);
if (file.exists())
return file.getPath();
else
return null;
}
first you must get list with all files in assets
private String [ ] listAssetFiles(String path) {
String [ ] list;
try {
list = getAssets().list(path);
if (list.length > 0) {
// T
his is a folder
for (String file : list) {
if (!listAssetFiles(path + "/" + file))
}
}
} catch (IOException e) {
return null;
}
return list;
}
and call listAssetFiles("")

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

Images from folder on sd card

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!

Picking an image for Wallpaper

I'm writing a live wallpaper and need some help. My wallpaper will create an effect over top of another image or existing wallpaper (not another live wallpaper) that the user chooses in the "Settings...".
My problem is this: I can't find a way to list the static wallpapers or images on the phone. I've seen some examples of getting the camera images, but not the wallpapers.
Any help would be appreciated.
If this helps, here's a FileFilter I wrote that will return a list of folders that contain images. You simply take a File representing a directory (I use it for Environment.getExternalStorageDirectory()) use .listFiles(filterForImageFolders) and it will return a File[] with the directories that contain images. You can then use this list to populate your list of images in your settings:
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
for (String ext : imageExtensions)
{
if (file.getName().endsWith("." + ext)) return true;
}
}
}
return false;
}
catch (SecurityException e)
{
Log.v("debug", "Access Denied");
return false;
}
}
};
(ImageExtensions is a String[] containing "png", "bmp", "jpg", "jpeg")

Categories

Resources