2015-10-07 82 views
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。如何解決這個問題,我用Google搜索了幾個小時,我真的不能找到一個解決的辦法不兼容類型:字符串不能轉換爲文件

+0

你傳遞一個'String' instead'of'File'的功能。 – dsharew

回答

1

這應該工作

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

這是一個快速回復謝謝!它解決了我的問題,我幾個小時都感到困惑 – NewBoy

1

使用文件的構造函數有兩個參數。第一個是目錄第二個文件或目的地目錄的名稱

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

這樣系統也會照顧分隔符。還要知道,

listFiles()可以返回null。所以,你應該檢查是否爲NULL值開始循環

0

嘗試像這樣(您需要處理異常太)前:

try{ 

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

}catch(FileNotFoundException ex){ 
    //ex handler code 
} 
相關問題