我在回收站 View 中列出了我所有的媒体文件。假设一个媒体文件在一个文件夹中,那么我也想在我的回收站 View 中显示该文件夹。 这是我列出媒体文件的代码
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()
}
如果文件夹中存在特定媒体文件,我还如何显示文件夹。任何帮助将不胜感激。
最佳答案
如果您获得使用存储访问框架访问任何文件夹的权限,您将获得该文件夹的 URI,您可以显示该文件夹、显示该文件夹内的文件、编辑或删除文件而无需再次使用 SAF,除非该文件夹不存在。它适用于设备内存和外部内存,如 SD 卡。如果您没有 Uri,imagSaveUriString 是字符串格式的 Uri,开始时在设备内设置一个默认文件夹,并使用 File dir = new File(Environment.getExternalStorageDirectory) 从该目录获取文件(), "应用目录");
我有一个图片库,其中列出了之前通过 SAF 授予权限的文件夹中扩展名为 .png 或 .jpeg 的图像
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);
}
}
}
}
}
然后设置我将数据发送到适配器
mAdapter = new GalleryListAdapter(this, listGalleryItems);
mRecyclerView.setAdapter(mAdapter);
FileUtils.isContentUri(imageSaveUriString) 检查 URI 是否为有效内容 URI 检查 "com.android.externalstorage.documents".equals(uri.getAuthority())
这是我使用的实用程序类,其中一些来自 SO,一些是我编写的,我认为这是一个完整的实用程序类,用于从中获取正确的 URI(文件:///和内容)和静态文件夹乌里。但是,您应该寻找存储访问框架。有一个 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());
}
}
关于android - 在 RecyclerView 中显示带有视频文件的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437217/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信