不兼容类型:无法将字符串转换为文件。

3
   GridView gv;
   ArrayList<File> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_yearbook);

    list = imageReader (Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mypath");

    gv = (GridView) findViewById(R.id.ImageGV);
    gv.setAdapter(new GridAdapter());
}


ArrayList<File> imageReader(File root) {

    ArrayList<File> a = new ArrayList<>();

    File[] files = root.listFiles();
    for (int i =0; i< files.length; i++) {
        if (files[i].isDirectory()) {
            a.addAll(imageReader(files[i]));
        }
        else {
            if ( files[i].getName().endsWith(".jpg")) {
                a.add(files[i]);
            }
        }
    }

    return a;
}

我试图让我的imageReader读取我的sdcard中的某个目录,以便在我的程序中显示一组图片。但是,在这行代码list = imageReader (Enviroment.getExternalStorageDirecctory().getAbsolutePath() + "/Mypath");中遇到了一个错误,它说 java.io.file 无法转换为 java.io.string。我该如何解决这个问题?我已经搜索了几个小时,但没有找到解决方案。


你正在将一个 String 而不是 File 传递给函数。 - dsharew
3个回答

2
使用带有两个参数的File构造函数。第一个参数是目录,第二个参数是文件名或目标目录的名称。
list = imageReader(new File(Environment.getExternalStorageDirectory(), "Mypath"))

这样系统也会处理分隔符。同时需要注意的是,listFiles() 可能会返回 null,所以在开始循环之前应该检查 null 值。


1
这应该可以工作。
list = imageReader(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mypath"));

那是一个快速的回复,谢谢!它解决了我的问题,我一直困惑了几个小时。 - NewBoy

0

像这样尝试一下(你还需要处理异常):

try{

list = imageReader(new File(Environment.getExternalStorageDirectory(), "Mypath"));

}catch(FileNotFoundException ex){
  //ex handler code
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接