android - 在我的应用程序中显示来自设备的所有图像

标签 android android-camera android-gallery android-external-storage

我正在使用下面的代码从 DCIM 中的相机文件夹中获取所有图像并显示在我的应用程序中。但是我想在我的应用程序中显示设备上的所有图像,而不管它们存储在设备上的什么位置。我该怎么做?

 String ExternalStorageDirectoryPath = Environment
                .getExternalStorageDirectory()
                .getAbsolutePath();
        String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera";
        images=new ArrayList<String>();
        File targetDirector = new File(targetPath);

        File[] files = targetDirector.listFiles();
        for (File file : files) {

            images.add(file.getAbsolutePath());
        }
        gallerylist=new CameraGalleryAdapter(getActivity().getApplicationContext(),R.layout.giphy_grid,images);
        gridview.setAdapter(gallerylist);

最佳答案

首先检查是否授予了所需的权限:

if (ActivityCompat.checkSelfPermission(CurrentActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
     ActivityCompat.requestPermissions(CurrentActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY)
}

然后你必须检查SD卡是否可用:

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

如果存在 SD 卡,则使用此:

final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
//Stores all the images from the gallery in Cursor
Cursor cursor = getContentResolver().query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
        null, orderBy);
//Total number of images
int count = cursor.getCount();

//Create an array to store path to all the images
String[] arrPath = new String[count];

for (int i = 0; i < count; i++) {
    cursor.moveToPosition(i);
    int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
    //Store the path of the image
    arrPath[i]= cursor.getString(dataColumnIndex);
    Log.i("PATH", arrPath[i]);
}
// The cursor should be freed up after use with close()
cursor.close();

上面的代码会列出SD卡中的所有图片,如果要从内存中获取图片,只需替换

MediaStore.Images.Media.EXTERNAL_CONTENT_URI

MediaStore.Images.Media.INTERNAL_CONTENT_URI

使用相同的代码 fragment 。

关于android - 在我的应用程序中显示来自设备的所有图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30777023/

相关文章:

android - 从图库中读取位图并将其写入 SD 卡失败

android - unity google play 服务和 admob 应用程序在打开时崩溃

android - 如何使用zxing库从一张图片中读取多个二维码

android - 将相机图像示例为位图 Android

android - Scroll完成后如何让GalleryView中的图片回到初始位置?

java - 选择一张图片而不是多张时出现android错误

Android以编程方式获取系统图标

android - recyclerView.setOnScrollChangeListener 不工作

Android 开发 - 回调 URL 无效... (0_o)

android - 是否可以为前后摄像头设置不同的摄像头参数?