kotlin 文件未重命名为Android 10

f0ofjuux  于 2022-12-30  发布在  Kotlin
关注(0)|答案(1)|浏览(172)

在Android 10上重命名文件时出现了一个问题,在其他版本上一切正常,无论大小。请帮助解决这个问题。我正在添加重命名发生的方法的一个片段。
'

private fun renameOperation() {
    var c = 0
    var fu: Uri
    for (item in list) {
        c += 1
        item.let { fileUri ->
            fu = fileUri
            contentResolver.query(fileUri, null, null, null, null)
        }?.use { returnCursor ->
            val nameIndex =
                returnCursor!!.getColumnIndex(OpenableColumns.DISPLAY_NAME)
            val sizeIndex = returnCursor!!.getColumnIndex(OpenableColumns.SIZE)

            returnCursor.moveToFirst()
            var id: Long = getIdFromDisplayName(returnCursor.getString(nameIndex))!!  //ERROR
            val fromUri = ContentUris.withAppendedId(MediaStore.Files.getContentUri("external"), id)
            ContentValues().also {
                try {

                    it.put(MediaStore.Files.FileColumns.IS_PENDING, 1)
                    contentResolver.update(fromUri, it, null, null)
                    it.clear()
                    it.put(MediaStore.Files.FileColumns.DISPLAY_NAME, "test1${c}")
                    it.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
                    contentResolver.update(fromUri, it, null, null)
                }
                catch (e: SecurityException){
                    Log.d("err", "err ===========================t: ${e} ")
                    val intentSender = when{
                        Build.VERSION.SDK_INT >= Build.VERSION_CODES.R ->{
                            MediaStore.createWriteRequest(contentResolver, listOf(fromUri))
                        }else -> null
                    }

                    intentSender?.let { sender ->
                        intentSenderLauncher.launch(
                            IntentSenderRequest.Builder(sender).build()
                        )
                    }
                }
            }

            Log.d("TAG", "path ===========================t: $fromUri ")
            Log.d(
                "TAG", "nameIndex ===========================t: ${
                    returnCursor.getString(nameIndex)
                } "
            )
            Log.d(
                "TAG", "sizeIndex ===========================t: ${
                    returnCursor.getLong(sizeIndex)
                } "
            )
        }
    }
}

'

fun getIdFromDisplayName(displayName: String): Long? {
    val projection: Array<String>
    projection = arrayOf(MediaStore.Files.FileColumns._ID)
    val cursor = contentResolver.query(
        extUri, projection,
        MediaStore.Files.FileColumns.DISPLAY_NAME + " LIKE ?", arrayOf(displayName), null
    )!!
    cursor.moveToFirst()
    if (cursor.count > 0) {
        val columnIndex = cursor.getColumnIndex(projection[0])
        val fileId = cursor.getLong(columnIndex)
        cursor.close()
        return fileId
    }
    return null
}

在这里,当尝试调用方法getIdFromDisplayName()时,会发生以下错误。代码用注解- //ERROR标记

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.rafiul.renameapp, PID: 6114
    java.lang.NullPointerException
        at com.rafiul.renameapp.MainActivity.renameOperation(MainActivity.kt:140)
        at com.rafiul.renameapp.MainActivity.onCreate$lambda-1(MainActivity.kt:54)
        at com.rafiul.renameapp.MainActivity.$r8$lambda$Tp1uLPbv4dOxJF0V-QS0nfEfk8Q(Unknown Source:0)
        at com.rafiul.renameapp.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:7125)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1131)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
W/System: A resource failed to call close.

'此解决方案不会在Android 10中重命名文件

val dir = File("/storage/emulated/0/Music")
    val oldFile = File(dir, "01. Tobu - Candyland.mp3")
    val newFile = File(dir, "Candyland.mp3")
    rename(oldFile, newFile)

}

fun rename(from: File, to: File) {
    if (from.exists() && to.exists()) {
        if (from.canWrite() && to.canWrite()) {
            if (from.renameTo(to)) {
                println("rename: " + to + "success")
            }
        }
    }
}

'

qmelpv7a

qmelpv7a1#

此方法对您有用:

public void rename(File from, File to) {
    if (from.exists()) {
        if (from.renameTo(to)) {
            Log.e(TAG, "rename: " + to + "success");
        }
    }
}

如何使用....

File dir = new File("storage/emulated/0/YOUR_PATH");
File oldFile = new File(dir, "oldName.png");
File newFile = new File(dir, "newName.png");
rename(oldFile, newFile);

不要忘记manifest.xml中的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 <application
    ...
    android:requestLegacyExternalStorage="true"
    ...>
        ...
 </application>

相关问题