2014-11-01 51 views
0

我試着去挑選僅是圖像文件和我成功了, 但現在的應用程序需要長時間來加載..如何只挑選圖像文件?

這裏是我的代碼的一部分:

的onCreate:

filename(testimg); 
      while (type != "jpeg" && type != "GIF" && type != "PNG" 
        && type != "BMP" && type != "WebP") { 
       filename(testimg); 
      } 

文件名(功能):

public void filename(File filename) { 
    abcd = filename.toString(); 
    File[] listFiles = filename.listFiles(); 
    Random r = new Random(); 
    File randomPicture = listFiles[r.nextInt(listFiles.length)]; 
    Uri pictureUri = Uri.fromFile(randomPicture); 

    convertedPath = randomPicture.getAbsolutePath(); 

    if (convertedPath.lastIndexOf(".") != -1) { 
     String ext = convertedPath 
       .substring(convertedPath.lastIndexOf(".") + 1); 
     MimeTypeMap mime = MimeTypeMap.getSingleton(); 
     type = mime.getExtensionFromMimeType(mime 
       .getMimeTypeFromExtension(ext)); 
     System.out.println(type); 
    } else { 
     type = null; 
    } 
    image.setImageURI(pictureUri); 
} 

所以我問是否有更有效的方法?

回答

0

我試着去挑選僅是圖像

爲什麼不直接使用OR文件?我覺得這是更好的:

while (type.equals("jpeg") || //more types) { 
       filename(testimg); 
      } 

因爲如果這些OR的任何一個TRUE,那麼它的圖像文件。

+0

@RolfSmit是的,謝謝:) – 2014-11-01 10:48:20

2
File[] listFiles = filename.listFiles(new FileFilter(){ 
@Override 
public boolean accept(File file){ 
return file.isFile() && (file.getName().endsWith(".jpg") || file.getName().endsWith(".png")); //add more extensions if needed 

} 
}); 
+0

最好的解決方案,這是我該怎麼做。但是這裏不要使用包含,使用endsWith! – 2014-11-01 09:02:40

+0

@RolfSmit指出 – 2014-11-01 11:31:04