不兼容类型:字符串不能转换为文件
问题描述:
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
。如何解决这个问题,我用Google搜索了几个小时,我真的不能找到一个解决的办法不兼容类型:字符串不能转换为文件
答
这应该工作
list = imageReader(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mypath"));
+0
这是一个快速回复谢谢!它解决了我的问题,我几个小时都感到困惑 – NewBoy
答
使用文件的构造函数有两个参数。第一个是目录第二个文件或目的地目录的名称
list = imageReader(new File(Environment.getExternalStorageDirectory(), "Mypath"))
这样系统也会照顾分隔符。还要知道,
listFiles()
可以返回null。所以,你应该检查是否为NULL值开始循环
答
尝试像这样(您需要处理异常太)前:
try{
list = imageReader(new File(Environment.getExternalStorageDirectory(), "Mypath"));
}catch(FileNotFoundException ex){
//ex handler code
}
你传递一个'String' instead'of'File'的功能。 – dsharew