0

I am trying to create a textpad in Android which will load any txt file and show the file. I have used import java.io.File and tried adding filter by following code but as dir.isDirectory() always returns true it add all the files in the list and my filter is not working. Please help if there is any problem with the code or any suggestions can add filter to my file explorer.

public class AndroidExplorer extends ListActivity {

private List<String> item = null;
private List<String> path = null;
private String root="/";
private TextView myPath;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myPath = (TextView)findViewById(R.id.path);
    getDir(root);
  }

private void getDir(String dirPath)
{
    FilenameFilter filter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String filename) {
            // TODO Auto-generated method stub
            if(dir.isDirectory())
            {
                System.out.println("%%%%%%%%%%%"+filename);
               return true;
            }
            else
            {
                System.out.println("*****"+filename);
                return filename.endsWith(".txt");
            }
        }
    };
    myPath.setText("Location: " + dirPath);

    item = new ArrayList<String>();
    path = new ArrayList<String>();
    File f = new File(dirPath);
    File[] files = f.listFiles(filter);

    if(!dirPath.equals(root))
    {

        item.add(root);
        path.add(root);

        item.add("../");
        path.add(f.getParent());

    }

    for(int i=0; i < files.length; i++)
    {
            File file = files[i];
            path.add(file.getPath());
            if(file.isDirectory())
                item.add(file.getName() + "/");
            else
                item.add(file.getName());
    }

    ArrayAdapter<String> fileList =
        new ArrayAdapter<String>(this, R.layout.row, item);
    setListAdapter(fileList);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    File file = new File(path.get(position));

    if (file.isDirectory())
    {
        if(file.canRead())
            getDir(path.get(position));
        else
        {
            new AlertDialog.Builder(this)
            .setIcon(R.drawable.icon)
            .setTitle("[" + file.getName() + "] folder can't be read!")
            .setPositiveButton("OK", 
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }).show();
        }
    }
    else
    {
        new AlertDialog.Builder(this)
            .setIcon(R.drawable.icon)
            .setTitle("[" + file.getName() + "]")
            .setPositiveButton("OK", 
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }).show();
    }
}
}
Vaandu
  • 4,857
  • 12
  • 49
  • 75
Mohit marwal
  • 251
  • 5
  • 12

2 Answers2

3

Your checking if the directory (dir) of the file is a directory in your filter. This will of course always be true. You need to check if the file itself is a directory. You'll have to convert the filename and directory into a new File object and check if that file represents a directory.

I'd recommend using a FileFilter instead of a FilenameFitler. It already has a file object that represents the file being filtered.

     FileFilter filter = new FileFilter() {

        @Override
        public boolean accept(File pathname) {
             if(pathname.isDirectory())
             {
                 System.out.println("%%%%%%%%%%%"+pathname);
                return true;
             }
             else
             {
                 System.out.println("*****"+pathname);
                 return pathname.getName().endsWith(".txt");
             }
        }
     };
Michael Krussel
  • 2,586
  • 1
  • 14
  • 16
0

If you are filtering TXT files, then why not filter on the extension of the file which is present in the name of the file?

if(dir.getName().endsWith(".txt") {
    // This is TXT file
}

EDIT :

To get the directory in which the file is present then use the following line of code in place of //This is TXT file

dir.getParent()

UPDATE :

did you try File.isFile()?

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
  • it will then not add the real directories as it will add only txt files to the list. – Mohit marwal Dec 29 '11 at 09:57
  • @ Adel Boutrosit will then not add the real directories as it will add only txt files to the list. Like in the root i have /data /sdcard folder it will also add these folders as its taking file and drectiores as one. it will check these folders also to end with txt and practically when i run the code with the above changes i got blank list as in the root i didnt have any text files and folder were not added – Mohit marwal Dec 29 '11 at 10:05
  • @user1120850 What exacly do you want to do because I think you are using my code wrongly – Adel Boutros Dec 29 '11 at 10:14
  • @ Adel Boutrosit i added if(dir.getName().endsWith(".txt") and dir.getparent in place of //This is TXT file as you have told. But at very first my path is root where we have various folders like system/, sdcard/ ,data/ ,root/ etc . So initialy it is checking dir.getName().endsWith(".txt") . Now as sdcard/ is a folder and it does not ends with "*.txt" it wont be added in the list. Similarly it wont add any folder in the list and my list is shown empty.so i am uable to browse futher. – Mohit marwal Dec 29 '11 at 10:29
  • I want list to display all the folders on my phone But show only files that ends with txt ie all text files – Mohit marwal Dec 29 '11 at 10:30
  • @user1120850 what does **File.getName()** contain when **File** is **sdcard/** ? – Adel Boutros Dec 29 '11 at 10:40
  • File.getName() contains sdcard for sdcard/ – Mohit marwal Dec 29 '11 at 10:57
  • @user1120850 Can you post your code after you added what I suggested. I am sensing that there is something wrong in it – Adel Boutros Dec 29 '11 at 11:15
  • File.isFile() is always false for both files as well as directory – Mohit marwal Dec 29 '11 at 12:08
  • This can't be right. You're doing something wrong. Please post the code after my fix. – Adel Boutros Dec 29 '11 at 13:08
  • @ Adel Boutros problem is solved if we use filefilter insted of filename filter........ But thanx for guiding me. – Mohit marwal Jan 02 '12 at 03:48