how to browse only text files from my application - android

i have built an application,where i am supposed to browse only for txt files in the device and read it.but i am not getting a valid solution to it.Like for example if we take whatsapp,there you can browse different files under different headings like under videos you will only browse videos and under gallery you will only browse images.but whats in case for text files only?is there any way?Please suggest.

try this.
//for example your folder present in sdcard/cts.
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/cts");
for (File wavfile : f.listFiles(new FileExtensionFilter()))
{
String str = wavfile.getName().toString();
}
//create a class and the filter based on your need file extension
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".txt") || name.endsWith(".TXT") );
}
}
thank you.

I would put your directories your searching into arrays... Loop the arrays and look for the file extensions after the " . " if its not a text extension remove it. Then display the new array to user like the photo gallery works or however else you would want to represent them.
Note- If you need access to these later you may want to be saving the path if the user say...needs to click and open them...
you may be able to use something to this effect for searching the SD Card
File file[] = Environment.getExternalStorageDirectory().listFiles();
file[i].getAbsolutePath();
Then search it for the extensions you want...

This will give you a file manager as you like. Just needs a bit of work around. But definitely helps
//fill method is to get the dir
private void fill(File f)
{
File[] dirs = f.listFiles();
this.setTitle("Current Dir: " + f.getName());
List<Option> dir = new ArrayList<Option>();
List<Option> fls = new ArrayList<Option>();
try
{
for (File ff : dirs)
{
if (ff.isDirectory())
{
dir.add(new Option(ff.getName(), "Folder", ff.getAbsolutePath()));
}
else
{
String filetype[] = objOption.getName().split("\\.");
if (filetype[(filetype.length) - 1].equals("txt")) {
fls.add(new Option(ff.getName(), "File Size: "+ ff.length()+" bytes", ff.getAbsolutePath()));
}
}
}
}
catch (Exception e)
{}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if (!f.getName().equalsIgnoreCase("sdcard"))
{
dir.add(0, new Option("..", "Parent Directory", f.getParent()));
}
adapter = new FileArrayAdapter(FileChooser.this, R.layout.dialog_file_view,dir);
lvFileList.setAdapter(adapter);
}

Related

Activity to search all music files (or a particular extension) in Android storage

I am building an Android app that writes files in the format of my custom .fire extension.
I need to access them all at once and put them in a ListView. Could someone please help me to fetch them via an activity or Async Task Manager?
You can write an Async Task to fetch the .fire files from the folder into which you are writing them initially and dynamically add the filenames into the listview.
You can do something like this in your async task:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/"+FolderWhichContainsyourFiles);
File[] listOfFiles = dir.listFiles();
for (int count = 0; count < listOfFiles.length; count++) {
File file = listOfFiles[count];
if (file.isFile() && file.getName().endsWith(".fire")) {
String fileName = file.getName();
//Here you can dynamically add this name into the ListView
}
}
}
You need to use an ArrayAdapter and add elements to the ArrayAdapter dynamically. It is brilliantly explained here: Dynamically add elements to a listView Android
if you want to find files recursively:
private static List<File> filesList = new ArrayList<File>();
public static List<File> recursiveList(String filePath) {
try {
File[] dir = new File(filePath).listFiles();
for (File item : dir) {
if (item.isDirectory()) recursiveList(item.getAbsolutePath());
else if (item.isFile() && item.getName().endsWith(".fire"))
filesList.add(item);
}
return filesList;
} catch (Exception e) {
return null;
}
}
and to retrieve files in activity:
List<File> files = recursiveList("/sdcard/Music/");
for (File file : files)
adapterFilesList.add("" + file.getName());

List each and every Folder and file

Plzzz help me with this. Already late searching for the solution:
I want to list each and every Folder and file which is in the Android Phone's Internal Memory and External Memory.
The below code only gets list of files in one single directory.. But I'm unable to understand how would I list all the folders and files from internal and external memory.
..... List files = getListFiles(new File("YOUR ROOT")); ....
private List getListFiles(File parentDir) {
ArrayList inFiles = new ArrayList();
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; }
Any help?
Look at the File object. It gives you methods to get all the files in a directory, tells you whether a file is a directory, and many other things.
You could easily do a recursive tree walk of the directory system. You probably will run into permissions issues, though, unless you have "rooted" your device.
I finally found this somewhere else.. This is how it's done (fully functional code)
public void walk(File root) {
File[] list = root.listFiles();
for (File f : list) {
if (f.isDirectory()) {
Log.d("realcrazy", "Dir: " + f.getAbsoluteFile());
walk(f);
}
else {
Log.d("realcrazy2", "File: " + f.getAbsoluteFile());
}
}
}

How to choose only .mp3 extension files from whole sdcard

In my application, when a user want to upload Audio, that user should only be able to choose .mp3 extension file. If the user choose any other file like .ppt, .pdf, it wont be allowed.
I have got this approved code for File explore from SD Card: Choose file dialog.
But I want only .mp3 extension files or list of .mp3 extension files.
So what should I do?
maybe you can check for files like this
File f = new File("/sdcard/");
for (File file : f.listFiles())
{
if(file.getName().endsWith(".mp3"))
{
// do something with them, add them to list or whatever
}
}
Check file pattern and then compare, if it is mp3 then add into arraylist, check below function, which will return list of mp3.
 Vector<String> mStrings =new Vector<String>();
int mTotalimage=0;
public void fileExtension(File dir) {
String mp3Pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
String mCheck=listFile[i].getAbsoluteFile().toString();
mCheck=mCheck.substring(mCheck.lastIndexOf("/")+1);
System.out.println("listFile[i].getAbsoluteFile().toString()"+listFile[i].getAbsoluteFile().toString());
System.out.println("mCheck..."+mCheck);
if (listFile[i].isDirectory() && !(mCheck.startsWith(".")) ) {
fileExtension(listFile[i]);
} else {
//fetch jpg from folders.
if (listFile[i].getName().endsWith(mp3Pattern)){
mStrings.add(listFile[i].getAbsolutePath().toString());
mTotalimage++;
//fetch png image from folders.
}
}
}
}
System.out.println("size on return......."+mStrings.size());
}

access android media directory?

ey up. ive built a simple music app that reads wav files from the sdcard and plays them.
how do i access the default media directory?
this is how i get the sdcard
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
File sd = new File(Environment.getExternalStorageDirectory ()); //this needs to be a folder the user can access, like media
as usual the docs dont give an actual example of usage but it says this - If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC...
how do i use it?
thank you
edit:
this makes it crash if i try to fill a spinner array with file path Strings.
File path = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
File sd = new File(path, "/myFolder");
File[] sdDirList = sd.listFiles(new WavFilter());
if (sdDirList != null)
{
//sort the spinner
amountofiles = sdDirList.length;
array_spinner=new String[amountofiles];
......
final Spinner s = (Spinner) findViewById(R.id.spinner1); //crashes here
ArrayAdapter<?> adapter = new ArrayAdapter<Object>(this,
android.R.layout.select_dialog_item, array_spinner);
EDIT2:
ok so ive done this test that is supposed to write a txt file to the music directory.
i run the app, no txt file is written anywhere on the device i can find.
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
String fname = "mytest.txt";
// Current state of the external media
String extState = Environment.getExternalStorageState();
// External media can be written onto
if (extState.equals(Environment.MEDIA_MOUNTED))
{
try {
// Make sure the path exists
boolean exists = (new File(path)).exists();
if (!exists){ new File(path).mkdirs(); }
// Open output stream
FileOutputStream fOut = new FileOutputStream(path + fname);
fOut.write("Test".getBytes());
// Close output stream
fOut.flush();
fOut.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
another edit: i will get this working!!
so if i use this line it creates a folder on the sdcard called 'Musictest'. dont understand??
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "test").getAbsolutePath();
////////////////////////////////////////////////////////////////////
Final Edit:
right so this will look for a folder called test in the devices music directory.
if it doesnt exist, it will be created.
(some fixing to be done here, error if empty) it then lists the files in the directory and adds them to an array.
public void LoadSounds() throws IOException
{
String extState = Environment.getExternalStorageState();
// Path to write files to
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/test").getAbsolutePath();
if(!extState.equals(Environment.MEDIA_MOUNTED)) {
//handle error here
}
else {
//do your file work here
// Make sure the path exists
boolean exists = (new File(path)).exists();
//if not create it
if (!exists){ new File(path).mkdirs(); }
File sd = new File(path);
//This will return an array with all the Files (directories and files)
//in the external storage folder
File[] sdDirList = sd.listFiles();
if (sdDirList != null)
{
//add the files to the spinner array
array_spinnerLoad=new String[sdDirList.length];
files = new String[sdDirList.length];
for(int i=0;i<sdDirList.length;i++){
array_spinnerLoad[i] = sdDirList[i].getName();
files[i] = sdDirList[i].getAbsolutePath();
}
}
}
}
as mentioned in the docs, getExternalFilesDir() return File. And File object can represent either file or directory.
Therefore:
File musicDirectory = new File( getExternalFilesDir(Environment.DIRECTORY_MUSIC));
Will give you the object to play with.

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!

Categories

Resources