简体   繁体   English

在我的应用中显示设备中的所有图像

[英]Displaying all images from device in my app

I am using code below to get all images from Camera folder inside DCIM and display in my app.我正在使用下面的代码从 DCIM 内的 Camera 文件夹中获取所有图像并显示在我的应用程序中。 But I want to display all images on the device in my app regardless of where they are stored on the device.但是我想在我的应用程序中显示设备上的所有图像,而不管它们存储在设备上的什么位置。 How can I do this?我怎样才能做到这一点?

 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);

First of all check if required permissions are granted:首先检查是否授予了所需的权限:

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)
}

Then you have to check if SD card is available:然后您必须检查 SD 卡是否可用:

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

If SD card is present then use this:如果存在 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();

The above code will list all images from SD card, For getting Images from Internal Memory just replace上面的代码将列出 SD 卡中的所有图像,要从内存中获取图像,只需替换

MediaStore.Images.Media.EXTERNAL_CONTENT_URI

with

MediaStore.Images.Media.INTERNAL_CONTENT_URI

Using the same snippet of code.使用相同的代码片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM