Load image files from internal storage into arrayList - java

I am busy developing an Android application for university and would like to load all images saved into an internal storage folder into an array list. I have managed to do it using assets but I need to be able to do it using the image files on the internal storage folder that I created
Code used to create the folder
File root_text = Environment.getExternalStorageDirectory();
try {
File folder = new File(Environment.getExternalStorageDirectory() + "/InkousticImages");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
}
Current code used to load asset files into an array list and open them into an inputStream(this is what I want to do but with the files from the internal storage instead)
String[] imageList = getAssets().list("images");
List <String> myList = new ArrayList<>();
for (String filename: imageList) {
if (filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith("jpeg")) {
myList.add(filename);
}
}
AssetManager assetManager = getAssets()
InputStream istr = assetManager.open("images/" + myList.toArray()[index]);
Any help would be greatly appreciated.

Here, I wrote the code for you, This loops over all the files in the directory and checks if the extension is a valid image and adds the name to the List
List<String> fileNames = new ArrayList<>();
File folder = new File(Environment.getExternalStorageDirectory(), "InkousticImages");
if (!folder.exists()) folder.mkdir();
for (File file : folder.listFiles()) {
String filename = file.getName().toLowerCase();
if (filename.endsWith(".jpg") || filename.endsWith("jpeg")) {
fileNames.add(filename);
}
}

Related

How to delete file in android?

I have used the android internal storage to save a file for my application.
Ex
File rootFolder = context.getFilesDir();
File albumIdFolder = new File(rootFolder,getAlbumId());
Basicaly i want to delete the folder
So i tried with
File rootFolder = context.getFilesDir();
File albumIdFolder = new File(rootFolder,getAlbumId());
albumIdFolder.delete()
but this not working not deleting folder
I readed this answares but not worked in my case please help me solve this issue i am not getting where i am going wong.
Delete file from internal storage
How to delete internal storage file in android?
Edit 2
Ex ^(folder hierarchy)
data
user
0
packageName
files
155775346846131
otherData
i want to delete 155775346846131 folder
You can delete files with folder like as below,
void deleteFiles(Context context) {
File rootFolder = context.getFilesDir();
File fileDir = new File( rootFolder,getAlbumId());
if (fileDir.exists()) {
File[] listFiles = fileDir.listFiles();
for (File listFile : listFiles) {
if (!listFile.delete()) {
System.err.println( "Unable to delete file: " + listFile );
}
}
}
rootFolder.delete();
}
Source : How to delete a whole folder and content?
Don't forgot to give Storage permission.
You can delete files and folders recursively like this:
public void deleteFolderRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
deleteFolderRecursive(child);
}
}
fileOrDirectory.delete();
}

Android Studio listFiles returns null with assets folder

In the assets folder I have another folder called songs with .txt files. I've been trying to put all .txt files in a File[ ] but I get a NullPointer on folder.listFiles().
Here's the code :
File folder = new File("assets/songs");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
String content = FileUtils.readFileToString(file);
this.list.add(content);
System.out.println(content);
}
}
return this.list;
Assets are not files on the device. They are files on the development machine. They are entries inside the APK file on the device.
Use AssetManager to work with assets, including its list() method.
As sir #CommonsWare mentioned, you can use AssetManager like this:
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
Note that this file is String array. So don't forget to initialize new file for each element of the array before iterating over it.

How to create File from folder in android assets?

I want to list all files in folder which is in assets. But new File("/android_asset/instagram").exists() always returns false.
File instagram = new File("/android_asset/instagram")
for (File lookUpFile : instagram.listFiles()) {
String filterName = FileUtils.removeExtension(lookUpFile.getName());
filterName = Strings.capitalizeAndCopy(filterName);
GPUImageLookupFilter lookupFilter = new GPUImageLookupFilter();
lookupFilter.setBitmap(BitmapFactory.decodeFile(lookUpFile.getAbsolutePath()));
filters.addFilter(filterName, lookupFilter);
}
Try to access the file using asset manager. Try to get the list of files and make sure its working.
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");

Retrieve all video files from all directories of SD card

I'm making a media player. I want to get all videos present in the sd card.
If the video is directly available in top directory of sd card, it is simple. But what about a video file exists in nested directory structure like
directory->directory->directory->file.mp4.
How can I search for a file in a nested directory structure?
You can create a list which can store the location of all the video files present on sd card. Run a loop which will visit every folder and update this array if given file format (in your case video files or .mp4) and add it to array. You can store this list onto persistent storage so as you can read it the next time your application is launched.
Here is sample code which can help you list all files in sdcard
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].isDirectory()) {
fileList.add(listFile[i]);
getfile(listFile[i]);
} else {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif")) {
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
With Apache FileUtils:
import org.apache.commons.io.FileUtils;
String path = ...;
String[] extensions = {"mp4", "mov", ...};
Collection<File> allMovies = FileUtils.listFiles(new File(path), extensions, true);
am posting this, maybe it would help some one in need.
as #Jaqen H'ghar said ... i just simplify the code to add the list of the extensions u want to show.
File filePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
List<String> fileList = new ArrayList<>();
String[] extensions = {"apk","mp3","mp4","or what ever extension u want"};
Collection<File> allMovies = FileUtils.listFiles(new File(String.valueOf(filePath)), extensions, true);
for (File file: allMovies) {
fileList.add(file.getName());
}

How to get all the filenames in android directory?

Im trying to list all the files in a particular folder of my android emulator and i keep getting null answer.
Heres my code:
File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
if (f.isFile())
String name = f.getName();
}
This doesnt seem to work dont know why.
I've split the function in two parts, first function gets all the files in the given path and the second function gets the filenames from the file array.
public File[] GetFiles(String DirectoryPath) {
File f = new File(DirectoryPath);
f.mkdirs();
File[] file = f.listFiles();
return file;
}
public ArrayList<String> getFileNames(File[] file){
ArrayList<String> arrayFiles = new ArrayList<String>();
if (file.length == 0)
return null;
else {
for (int i=0; i<file.length; i++)
arrayFiles.add(file[i].getName());
}
return arrayFiles;
}
change
File[] file= new File(sdCardRoot+"path");
with
File[] file= new File(sdCardRoot, "path");
and make sure the directory path exits
Just Check this:
List<File> files = getListFiles(new File("YOUR ROOT"));
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
}
return inFiles;
Since sdCardRoot is instance of File, sdCardRoot+"path" will return the same thing as sdCardRoot.toString() + "path".
However, calling file.toString() returns file name, but not absolute path. You need to call sdCardRoot.getAbsolutePath() + "path".
Also, make sure that you have allowed the emulator to use a certain amount of memory for external storage.

Categories