Android Java FileNameFilter

时间:2016-02-28 13:49:42

标签: java android filter filenames alertdialog

我在编程方面遇到了一些问题。我没有什么问题。 我的任务: 我必须扫描外部SD卡和内部,以查找扩展名为.mp3的文件,并在AlertDialog中显示此格式(扩展名)中所有文件的名称 请帮我。 代码:

private AlertDialog mIconSelectorDialog;

private String dir = "/storage/emulated/0/Music";
private String ext = ".mp3";
private static File[] listFiles;
private final static String[]list = new String[]{};
private final static String[]dirList = new String[]{};
AlertDialog.Builder builder;

    public static void findFiles(String dir,String ext){
    File file = new File(dir);
    listFiles = file.listFiles(new MyFileNameFilter(ext));

    for(File f : listFiles){
        dirList[dirList.length+1] = (dir+File.separator+f.getName());
    }
    for(File f : listFiles){
        list[list.length+1] = (f.getName());
    }
}
public static class MyFileNameFilter implements FilenameFilter {
    private String ext;
    public  MyFileNameFilter(String ext){
        this.ext = ext;
    }
    @Override
    public boolean accept(File dir , String name){
        return name.toLowerCase().contains(ext.toLowerCase());
    }
}
 public void musicSelector(View view){
    findFiles(dir,ext);
onCreateDialog();
    /*protected Dialog onCretateDialog(){
        builder = new AlertDialog.Builder(this);
        builder.setTitle("");
        builder.setItems(list, myClickListner());
        return builder.create();

    }*/
}


protected Dialog onCreateDialog() {

    builder = new AlertDialog.Builder(this);
    builder.setTitle("Choose your Sound"); // заголовок для диалога

    builder.setItems(list, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            // TODO Auto-generated method stub
            sound = list[item];
            dirSound = dirList[item];
            Toast.makeText(getApplicationContext(),
                    "Your Song: " + list[item],
                    Toast.LENGTH_SHORT).show();
        }
    });
    builder.setCancelable(false);
    return builder.create();
}

1 个答案:

答案 0 :(得分:0)

Java中的数组是固定大小的,它们不会自动扩展以容纳更多值。您可以从一开始就创建正确大小的数组:

list = new String[listFiles.length];
for(int i=0; i<listFiles.length; i++){
    list[i] = listFiles[i].getName();
}

或者您可以使用ArrayList

List<String> nameList = new ArrayList<String>();
for(File f : listFiles){
    nameList.add(f.getName());
}