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