应用程序找不到SD卡内的图像目录

时间:2014-07-09 04:27:14

标签: java android

大家好我正在创建一个将在gridview中显示图像的应用程序,但问题是应用程序找不到SD卡内的图像目录。

这是代码。

public class Utils {

private Context _context;

public Utils(Context context) {
    this._context = context;
}

public ArrayList<String> getFilePaths() {
    ArrayList<String> filePaths = new ArrayList<String>();

    File directory = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
                                + AppConstant.PHOTO_ALBUM);

    if(directory.isDirectory()) {
        File[] listFiles = directory.listFiles();

    if(listFiles.length > 0) {

        for(int i = 0; i < listFiles.length; i++) {

            String filePath = listFiles[i].getAbsolutePath();

            if(IsSupportedFile(filePath)) {
                filePaths.add(filePath);
            }

            }

        }
    else {
        Toast.makeText(_context, AppConstant.PHOTO_ALBUM + "is empty. Please load some images", Toast.LENGTH_LONG).show();
        }
    }
    else {
        AlertDialog.Builder alert = new AlertDialog.Builder(_context);
        alert.setTitle("Error!");
        alert.setMessage(AppConstant.PHOTO_ALBUM + " directory path is not valid!");
        alert.setPositiveButton("OK", null);
        alert.show();
    }
    return filePaths;
}

private boolean IsSupportedFile(String filePath) {
    String ext = filePath.substring((filePath.lastIndexOf(".") + 1), filePath.length());

    if(AppConstant.FILE_EXTENSION.contains(ext.toLowerCase(Locale.getDefault()))) 
        return true;
    else
        return false;
}

public int getScreenWidth() {
    int columnWidth;

    WindowManager wm = (WindowManager) _context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();

    final Point point = new Point();
    try {
        display.getSize(point);
    } catch(java.lang.NoSuchMethodError ignore) {
        point.x = display.getWidth();
        point.y = display.getHeight();
    }

    columnWidth = point.x;
    return columnWidth;
}

希望你能帮助我这些家伙..我不知道如何通过使用该功能访问SD卡

2 个答案:

答案 0 :(得分:1)

我的代码没有任何问题。只需确保用户已在清单上授予了应用程序权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

答案 1 :(得分:0)

要写入外部存储,您必须在清单中声明:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />