Android 在RecyclerView中显示包含视频文件的文件夹
我在“回收器”视图中列出了我的所有媒体文件。假设一个媒体文件在一个文件夹中,那么我也想在我的回收器视图中显示该文件夹。 这是我列出媒体文件的代码Android 在RecyclerView中显示包含视频文件的文件夹,android,android-recyclerview,kotlin,mediastore,Android,Android Recyclerview,Kotlin,Mediastore,我在“回收器”视图中列出了我的所有媒体文件。假设一个媒体文件在一个文件夹中,那么我也想在我的回收器视图中显示该文件夹。 这是我列出媒体文件的代码 var projection = arrayOf(MediaStore.Video.Media.DISPLAY_NAME) var cursor = CursorLoader(applicationContext, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null, n
var projection = arrayOf(MediaStore.Video.Media.DISPLAY_NAME)
var cursor = CursorLoader(applicationContext, MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null).loadInBackground()
if (cursor != null) {
while (cursor.moveToNext()) {
val name = cursor.getString(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DISPLAY_NAME))
Log.i("Main", name)
}
cursor.close()
}
如果文件夹中存在特定的媒体文件,如何显示该文件夹。非常感谢您的帮助。如果您获得使用Storage access Framework访问任何文件夹的权限,您将获得该文件夹的URI,您可以显示该文件夹,显示该文件夹中的文件,编辑或删除文件,而无需再次使用SAF,除非该文件夹不存在。它既适用于设备存储器,也适用于SD卡等外部存储器。如果您没有Uri,
imagSaveUriString
是字符串格式的Uri,在开始时在设备内设置一个默认文件夹,并使用File dir=new File(Environment.getExternalStorageDirectory(),“App dir”)从该目录获取文件代码>
我有一个图像库,其中列出了文件夹中扩展名为.png或.jpeg的图像,该文件夹之前通过SAF获得了权限
private void setUpGalleryData() {
listGalleryItems.clear();
if (FileUtils.isContentUri(imageSaveUriString)) {
DocumentFile dir = DocumentFile.fromTreeUri(getApplicationContext(), Uri.parse(imageSaveUriString));
DocumentFile[] documentFiles = dir.listFiles();
if (dir != null && documentFiles != null && documentFiles.length > 0) {
for (int i = 0; i < documentFiles.length; i++) {
if (documentFiles[i].getUri().toString().toLowerCase().endsWith(Config.IMAGE_FORMAT_JPEG)
|| documentFiles[i].getUri().toString().toLowerCase().endsWith(Config.IMAGE_FORMAT_PNG)) {
GalleryItem galleryItem = new GalleryItem();
galleryItem.setName(documentFiles[i].getName());
galleryItem.setSize(documentFiles[i].length());
galleryItem.setPath(documentFiles[i].getUri().toString());
galleryItem.setDateLastModified(documentFiles[i].lastModified());
listGalleryItems.add(galleryItem);
}
}
}
} else {
File dir = new File(Environment.getExternalStorageDirectory(), Config.APP_DIRECTORY);
File[] files = dir.listFiles();
if (dir != null && files != null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
if (files[i].getAbsolutePath().endsWith(".jpg") || files[i].getAbsolutePath().endsWith(".png")) {
GalleryItem galleryItem = new GalleryItem();
galleryItem.setName(files[i].getName());
galleryItem.setSize(files[i].length());
galleryItem.setPath(files[i].getAbsolutePath());
galleryItem.setDateLastModified(files[i].lastModified());
listGalleryItems.add(galleryItem);
}
}
}
}
}
FileUtils.isContentUri(imageSaveUriString)
检查URI是否为有效的内容URI检查“com.android.externalstorage.documents”。等于(URI.getAuthority())
这是我使用的实用程序类,我从中获得了一些,一些是我自己编写的,我认为这是一个完整的util类,可以从URI中获得正确的URI(file:///和content)和静态文件夹。但是,您应该寻找存储访问框架。有一个Google示例显示如何创建子文件夹和在文件夹中查找文件夹
public final class FileUtils {
private FileUtils() {
}
private static final String LOG_TAG = FileUtils.class.getName();
/**
* Get absolute paths of memory and SD cards
*
* @param context
* Required for getting external starage dirs
* @return returns external storage paths (directory of external memory card) as
* array of Strings
*/
public static String[] getExternalStorageDirectories(Context context) {
List<String> results = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Method 1 for KitKat & above
File[] externalDirs = context.getExternalFilesDirs(null);
for (File file : externalDirs) {
String path = file.getPath().split("/Android")[0];
boolean addPath = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
addPath = Environment.isExternalStorageRemovable(file);
} else {
addPath = Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(file));
}
if (addPath) {
results.add(path);
}
}
}
if (results.isEmpty()) { // Method 2 for all versions
// better variation of: http://stackoverflow.com/a/40123073/5002496
String output = "";
try {
final Process process = new ProcessBuilder().command("mount | grep /dev/block/vold")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
output = output + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
if (!output.trim().isEmpty()) {
String devicePoints[] = output.split("\n");
for (String voldPoint : devicePoints) {
results.add(voldPoint.split(" ")[2]);
}
}
}
// Below few lines is to remove paths which may not be external memory card,
// like OTG (feel free to comment them out)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i < results.size(); i++) {
if (!results.get(i).toLowerCase().matches(".*[0-9a-f]{4}[-][0-9a-f]{4}")) {
Log.d(LOG_TAG, results.get(i) + " might not be extSDcard");
results.remove(i--);
}
}
} else {
for (int i = 0; i < results.size(); i++) {
if (!results.get(i).toLowerCase().contains("ext") && !results.get(i).toLowerCase().contains("sdcard")) {
Log.d(LOG_TAG, results.get(i) + " might not be extSDcard");
results.remove(i--);
}
}
}
String[] storageDirectories = new String[results.size()];
for (int i = 0; i < results.size(); ++i)
storageDirectories[i] = results.get(i);
return storageDirectories;
}
/**
* Gets File from DocumentFile if Uri is File Uri starting with file:///
*
* @param documentFile
* Document file that contains Uri to create File from
* @return File with absolute path to the physical file on device's memory
*/
public static File getFileFromFileUri(DocumentFile documentFile) {
try {
File file = new File(URI.create(documentFile.getUri().toString()));
return file;
} catch (Exception e) {
return null;
}
}
/**
* Returns File with absolute path to physical file in memory. Uri should be a
* valid File Uri starting with file:///
*
* @param uriString
* Should contain a valid File Uri path
* @return File pointing to physical file in memory
*/
public static File getFileFromFileUri(String uriString) {
try {
Uri uri = Uri.parse(uriString);
File file = new File(URI.create(uri.toString()));
return file;
} catch (Exception e) {
return null;
}
}
/**
* Gets absolute path of a file in SD Card if Uri of Document file is content
* Uri content:// .
*
* @param documentFile
* DocumentFile Uri is content uri
* @return Absolute path of the file
*/
public static String getSDCardPath(DocumentFile documentFile) {
// We can't get absolute path from DocumentFile or Uri.
// It is a hack to build absolute path by DocumentFile.
// May not work on some devices.
try {
Uri uri = documentFile.getUri();
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
String sd = null;
sd = System.getenv("SECONDARY_STORAGE");
if (sd == null) {
// sd = System.getenv("EXTERNAL_STORAGE");
String documentPath = "/storage" + "/" + docId.replace(":", "/");
return documentPath;
}
if (sd != null) {
// On some devices SECONDARY_STORAGE has several paths
// separated with a colon (":"). This is why we split
// the String.
String[] paths = sd.split(":");
for (String p : paths) {
File fileSD = new File(p);
if (fileSD.isDirectory()) {
sd = fileSD.getAbsolutePath();
}
}
String id = split[1];
String documentPath = sd + "/" + id;
return documentPath;
}
} catch (Exception e) {
System.out.println("FileUtils ERROR " + e.toString());
return null;
}
return null;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and other
* file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
try {
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isContentUri(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1] + "/";
} else {
return Environment.getExternalStorageDirectory() + "/";
}
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for MediaStore
* Uris, and other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Checks if a string is parsable to Content Uri
*
* @param uriString
* checked if can be parsed to a Content Uri
* @return uriString is a content uri
*/
public static boolean isContentUri(String uriString) {
Uri uri = null;
try {
uri = Uri.parse(uriString);
} catch (NullPointerException e) {
return false;
}
return isContentUri(uri);
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isContentUri(Uri uri) {
if (uri == null) {
return false;
} else {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
公共最终类文件utils{
私有文件utils(){
}
私有静态最终字符串LOG_TAG=FileUtils.class.getName();
/**
*获取内存和SD卡的绝对路径
*
*@param上下文
*获取外部starage目录所需
*@return将外部存储路径(外部存储卡目录)返回为
*字符串数组
*/
公共静态字符串[]GetExternalStorageDirectory(上下文){
列表结果=新建ArrayList();
if(Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.KITKAT){//KITKAT以上的方法1
文件[]externalDirs=context.getExternalFilesDirs(null);
for(文件:externalDirs){
字符串路径=file.getPath().split(“/Android”)[0];
布尔addPath=false;
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.LOLLIPOP){
addPath=Environment.isExternalStorageRemovable(文件);
}否则{
addPath=Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(文件));
}
if(addPath){
结果。添加(路径);
}
}
}
如果(results.isEmpty()){//所有版本的方法2
//更好地改变:http://stackoverflow.com/a/40123073/5002496
字符串输出=”;
试一试{
final Process=new ProcessBuilder().命令(“mount | grep/dev/block/vold”)
.redirectErrorStream(true).start();
process.waitFor();
最终的InputStream=process.getInputStream();
最终字节[]缓冲区=新字节[1024];
while(is.read(buffer)!=-1){
输出=输出+新字符串(缓冲区);
}
is.close();
}捕获(最终异常e){
e、 printStackTrace();
}
如果(!output.trim().isEmpty()){
字符串devicePoints[]=output.split(“\n”);
for(字符串卷点:设备点){
结果.添加(voldPoint.split(“”[2]);
}
}
}
//下面几行是删除可能不是外部存储卡的路径,
//像OTG(请随意评论)
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.M){
对于(int i=0;i public final class FileUtils {
private FileUtils() {
}
private static final String LOG_TAG = FileUtils.class.getName();
/**
* Get absolute paths of memory and SD cards
*
* @param context
* Required for getting external starage dirs
* @return returns external storage paths (directory of external memory card) as
* array of Strings
*/
public static String[] getExternalStorageDirectories(Context context) {
List<String> results = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Method 1 for KitKat & above
File[] externalDirs = context.getExternalFilesDirs(null);
for (File file : externalDirs) {
String path = file.getPath().split("/Android")[0];
boolean addPath = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
addPath = Environment.isExternalStorageRemovable(file);
} else {
addPath = Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(file));
}
if (addPath) {
results.add(path);
}
}
}
if (results.isEmpty()) { // Method 2 for all versions
// better variation of: http://stackoverflow.com/a/40123073/5002496
String output = "";
try {
final Process process = new ProcessBuilder().command("mount | grep /dev/block/vold")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
output = output + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
if (!output.trim().isEmpty()) {
String devicePoints[] = output.split("\n");
for (String voldPoint : devicePoints) {
results.add(voldPoint.split(" ")[2]);
}
}
}
// Below few lines is to remove paths which may not be external memory card,
// like OTG (feel free to comment them out)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i < results.size(); i++) {
if (!results.get(i).toLowerCase().matches(".*[0-9a-f]{4}[-][0-9a-f]{4}")) {
Log.d(LOG_TAG, results.get(i) + " might not be extSDcard");
results.remove(i--);
}
}
} else {
for (int i = 0; i < results.size(); i++) {
if (!results.get(i).toLowerCase().contains("ext") && !results.get(i).toLowerCase().contains("sdcard")) {
Log.d(LOG_TAG, results.get(i) + " might not be extSDcard");
results.remove(i--);
}
}
}
String[] storageDirectories = new String[results.size()];
for (int i = 0; i < results.size(); ++i)
storageDirectories[i] = results.get(i);
return storageDirectories;
}
/**
* Gets File from DocumentFile if Uri is File Uri starting with file:///
*
* @param documentFile
* Document file that contains Uri to create File from
* @return File with absolute path to the physical file on device's memory
*/
public static File getFileFromFileUri(DocumentFile documentFile) {
try {
File file = new File(URI.create(documentFile.getUri().toString()));
return file;
} catch (Exception e) {
return null;
}
}
/**
* Returns File with absolute path to physical file in memory. Uri should be a
* valid File Uri starting with file:///
*
* @param uriString
* Should contain a valid File Uri path
* @return File pointing to physical file in memory
*/
public static File getFileFromFileUri(String uriString) {
try {
Uri uri = Uri.parse(uriString);
File file = new File(URI.create(uri.toString()));
return file;
} catch (Exception e) {
return null;
}
}
/**
* Gets absolute path of a file in SD Card if Uri of Document file is content
* Uri content:// .
*
* @param documentFile
* DocumentFile Uri is content uri
* @return Absolute path of the file
*/
public static String getSDCardPath(DocumentFile documentFile) {
// We can't get absolute path from DocumentFile or Uri.
// It is a hack to build absolute path by DocumentFile.
// May not work on some devices.
try {
Uri uri = documentFile.getUri();
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
String sd = null;
sd = System.getenv("SECONDARY_STORAGE");
if (sd == null) {
// sd = System.getenv("EXTERNAL_STORAGE");
String documentPath = "/storage" + "/" + docId.replace(":", "/");
return documentPath;
}
if (sd != null) {
// On some devices SECONDARY_STORAGE has several paths
// separated with a colon (":"). This is why we split
// the String.
String[] paths = sd.split(":");
for (String p : paths) {
File fileSD = new File(p);
if (fileSD.isDirectory()) {
sd = fileSD.getAbsolutePath();
}
}
String id = split[1];
String documentPath = sd + "/" + id;
return documentPath;
}
} catch (Exception e) {
System.out.println("FileUtils ERROR " + e.toString());
return null;
}
return null;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and other
* file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
try {
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isContentUri(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1] + "/";
} else {
return Environment.getExternalStorageDirectory() + "/";
}
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for MediaStore
* Uris, and other file-based ContentProviders.
*
* @param context
* The context.
* @param uri
* The Uri to query.
* @param selection
* (Optional) Filter used in the query.
* @param selectionArgs
* (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Checks if a string is parsable to Content Uri
*
* @param uriString
* checked if can be parsed to a Content Uri
* @return uriString is a content uri
*/
public static boolean isContentUri(String uriString) {
Uri uri = null;
try {
uri = Uri.parse(uriString);
} catch (NullPointerException e) {
return false;
}
return isContentUri(uri);
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isContentUri(Uri uri) {
if (uri == null) {
return false;
} else {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri
* The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}