选择外部存储中的文件并获取路径

发布于 2025-01-16 05:49:07 字数 5401 浏览 1 评论 0原文

我知道这个问题已经被问过好几次了,但我能找到的所有内容都只在 Java 中,与我不太相关...... 当我单击应用程序中的按钮时,我试图选择一个文件(图像或视频,例如: /storage/emulated/0/Download/giphy.gif ),并且当选择图片或视频时,我需要路径进入编辑文本。 我在 kotlin 中找到了路径的代码:

    class URIPathHelper {

    fun getPath(context: Context, uri: Uri): String? {
        val isKitKatorAbove = true

        // DocumentProvider
        if (isKitKatorAbove && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                val docId = DocumentsContract.getDocumentId(uri)
                val split = docId.split(":".toRegex()).toTypedArray()
                val type = split[0]
                if ("primary".equals(type, ignoreCase = true)) {
                    return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
                }

            } else if (isDownloadsDocument(uri)) {
                val id = DocumentsContract.getDocumentId(uri)
                val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id))
                return getDataColumn(context, contentUri, null, null)
            } else if (isMediaDocument(uri)) {
                val docId = DocumentsContract.getDocumentId(uri)
                val split = docId.split(":".toRegex()).toTypedArray()
                val type = split[0]
                var contentUri: Uri? = null
                if ("image" == type) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                } else if ("video" == type) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                } else if ("audio" == type) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                }
                val selection = "_id=?"
                val selectionArgs = arrayOf(split[1])
                return getDataColumn(context, contentUri, selection, selectionArgs)
            }
        } else if ("content".equals(uri.scheme, ignoreCase = true)) {
            return getDataColumn(context, uri, null, null)
        } else if ("file".equals(uri.scheme, ignoreCase = true)) {
            return uri.path
        }
        return null
    }

    fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
        var cursor: Cursor? = null
        val column = "_data"
        val projection = arrayOf(column)
        try {
            cursor = uri?.let { context.getContentResolver().query(it, projection, selection, selectionArgs,null) }
            if (cursor != null && cursor.moveToFirst()) {
                val column_index: Int = cursor.getColumnIndexOrThrow(column)
                return cursor.getString(column_index)
            }
        } finally {
            if (cursor != null) cursor.close()
        }
        return null
    }

    fun isExternalStorageDocument(uri: Uri): Boolean {
        return "com.android.externalstorage.documents" == uri.authority
    }

    fun isDownloadsDocument(uri: Uri): Boolean {
        return "com.android.providers.downloads.documents" == uri.authority
    }

    fun isMediaDocument(uri: Uri): Boolean {
        return "com.android.providers.media.documents" == uri.authority
    }
}

这就是我正在尝试的:

    binding.redloader.setOnClickListener {
            val uriPathHelper = URIPathHelper()
            val filePath: String? = uriPathHelper.getPath(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            val uri: Uri = Uri.parse(filePath)
            val intent = Intent(Intent.ACTION_VIEW)
            intent.type = "image/*"
            intent.putExtra(Intent.ACTION_VIEW, uri)
            startActivity(Intent.createChooser(intent, "Open file"))
            binding.redgif.setText(filePath)
        }

当我单击按钮时,它会自动选择存储中的第一张图片,然后打开谷歌图片,但除了观看图片之外我什么也做不了... 很抱歉,我知道它们是我的代码中的一些愚蠢的东西,我认为我与意图有关,但我在互联网上看到的只是调用 private void ,它对我不起作用...... 我是一个完全的初学者,我真的希望有人可以帮助我...

更新我正在尝试的内容,我想我已经接近了:

binding.redloader.setOnClickListener {
        val uriPathHelper = URIPathHelper()
        intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"

        intent.addCategory(Intent.CATEGORY_OPENABLE)

        intent = Intent.createChooser(intent, "Choose a file")
        val resultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val data: Intent? = result.data
                    if (data != null) {
                        val fileUri: Uri? = data.data
                        Log.i(LOG_TAG, fileUri.toString())

                        var fileURIPathHelper: String? = null
                        try {
                            fileURIPathHelper = uriPathHelper.getPath(this, EXTERNAL_CONTENT_URI)
                        } catch (e: Exception) {
                            Log.e(LOG_TAG, "Error: " + e)
                            Toast.makeText(this, "Error: " + e, Toast.LENGTH_SHORT).show()
                        }
                        this.binding.redgif.setText(fileURIPathHelper)
                    }
                }
            }
            resultLauncher.launch(intent)
    }

i know this question has been asked several times but everything i can find is only in Java and not very relevant to me...
I'm trying to select a file when i click on a button in my app (images or videos like : /storage/emulated/0/Download/giphy.gif ) and the when the picture or video is selected, i need the path to go inside an edittext.
I have found that code in kotlin for path :

    class URIPathHelper {

    fun getPath(context: Context, uri: Uri): String? {
        val isKitKatorAbove = true

        // DocumentProvider
        if (isKitKatorAbove && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                val docId = DocumentsContract.getDocumentId(uri)
                val split = docId.split(":".toRegex()).toTypedArray()
                val type = split[0]
                if ("primary".equals(type, ignoreCase = true)) {
                    return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
                }

            } else if (isDownloadsDocument(uri)) {
                val id = DocumentsContract.getDocumentId(uri)
                val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id))
                return getDataColumn(context, contentUri, null, null)
            } else if (isMediaDocument(uri)) {
                val docId = DocumentsContract.getDocumentId(uri)
                val split = docId.split(":".toRegex()).toTypedArray()
                val type = split[0]
                var contentUri: Uri? = null
                if ("image" == type) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                } else if ("video" == type) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                } else if ("audio" == type) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                }
                val selection = "_id=?"
                val selectionArgs = arrayOf(split[1])
                return getDataColumn(context, contentUri, selection, selectionArgs)
            }
        } else if ("content".equals(uri.scheme, ignoreCase = true)) {
            return getDataColumn(context, uri, null, null)
        } else if ("file".equals(uri.scheme, ignoreCase = true)) {
            return uri.path
        }
        return null
    }

    fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
        var cursor: Cursor? = null
        val column = "_data"
        val projection = arrayOf(column)
        try {
            cursor = uri?.let { context.getContentResolver().query(it, projection, selection, selectionArgs,null) }
            if (cursor != null && cursor.moveToFirst()) {
                val column_index: Int = cursor.getColumnIndexOrThrow(column)
                return cursor.getString(column_index)
            }
        } finally {
            if (cursor != null) cursor.close()
        }
        return null
    }

    fun isExternalStorageDocument(uri: Uri): Boolean {
        return "com.android.externalstorage.documents" == uri.authority
    }

    fun isDownloadsDocument(uri: Uri): Boolean {
        return "com.android.providers.downloads.documents" == uri.authority
    }

    fun isMediaDocument(uri: Uri): Boolean {
        return "com.android.providers.media.documents" == uri.authority
    }
}

And this is what i'm trying :

    binding.redloader.setOnClickListener {
            val uriPathHelper = URIPathHelper()
            val filePath: String? = uriPathHelper.getPath(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            val uri: Uri = Uri.parse(filePath)
            val intent = Intent(Intent.ACTION_VIEW)
            intent.type = "image/*"
            intent.putExtra(Intent.ACTION_VIEW, uri)
            startActivity(Intent.createChooser(intent, "Open file"))
            binding.redgif.setText(filePath)
        }

When I click on the button it automatically chooses the first picture in the storage, and then it opens google picture but I cannot do anything except watch the pictures...
I'm sorry I know they are some stupid things in my code, I think I have something to do with intent but all I see on the internet is calling private void and it is not working for me...
I'm a complete beginner and I really hope someone can help me...

Update with what i'm trying, i think i'm close :

binding.redloader.setOnClickListener {
        val uriPathHelper = URIPathHelper()
        intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"

        intent.addCategory(Intent.CATEGORY_OPENABLE)

        intent = Intent.createChooser(intent, "Choose a file")
        val resultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val data: Intent? = result.data
                    if (data != null) {
                        val fileUri: Uri? = data.data
                        Log.i(LOG_TAG, fileUri.toString())

                        var fileURIPathHelper: String? = null
                        try {
                            fileURIPathHelper = uriPathHelper.getPath(this, EXTERNAL_CONTENT_URI)
                        } catch (e: Exception) {
                            Log.e(LOG_TAG, "Error: " + e)
                            Toast.makeText(this, "Error: " + e, Toast.LENGTH_SHORT).show()
                        }
                        this.binding.redgif.setText(fileURIPathHelper)
                    }
                }
            }
            resultLauncher.launch(intent)
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何处潇湘 2025-01-23 05:49:07

我解决了! :)

val resultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val data: Intent? = result.data
                    if (data != null) {
                        val fileUri: Uri? = data.data
                        Log.i(PackageManagerCompat.LOG_TAG, fileUri.toString())

                        val contentUri: String?
                        try {
                            contentUri = uriPathHelper.getPath(this, fileUri!!)
                            this.binding.redgif.setText(contentUri)
                        } catch (e: Exception) {
                            Log.e(PackageManagerCompat.LOG_TAG, "Error: " + e)
                            Toast.makeText(this, "Error: " + e, Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
    binding.redloader.setOnClickListener {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivity(Intent.createChooser(intent, "Open file"))
        resultLauncher.launch(intent)
    }

I solved it ! :)

val resultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    val data: Intent? = result.data
                    if (data != null) {
                        val fileUri: Uri? = data.data
                        Log.i(PackageManagerCompat.LOG_TAG, fileUri.toString())

                        val contentUri: String?
                        try {
                            contentUri = uriPathHelper.getPath(this, fileUri!!)
                            this.binding.redgif.setText(contentUri)
                        } catch (e: Exception) {
                            Log.e(PackageManagerCompat.LOG_TAG, "Error: " + e)
                            Toast.makeText(this, "Error: " + e, Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }
    binding.redloader.setOnClickListener {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivity(Intent.createChooser(intent, "Open file"))
        resultLauncher.launch(intent)
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文