Commit c0c1b87e authored by Leonardo Aramaki's avatar Leonardo Aramaki

Implement more reliable way to get file size

parent aa4e1bc8
...@@ -9,10 +9,7 @@ import android.provider.DocumentsContract ...@@ -9,10 +9,7 @@ import android.provider.DocumentsContract
import android.provider.MediaStore import android.provider.MediaStore
import android.provider.OpenableColumns import android.provider.OpenableColumns
import android.webkit.MimeTypeMap import android.webkit.MimeTypeMap
import java.io.FileInputStream import java.io.*
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
fun Uri.getFileName(context: Context): String? { fun Uri.getFileName(context: Context): String? {
val cursor = context.contentResolver.query(this, null, null, null, null, null) val cursor = context.contentResolver.query(this, null, null, null, null, null)
...@@ -27,16 +24,22 @@ fun Uri.getFileName(context: Context): String? { ...@@ -27,16 +24,22 @@ fun Uri.getFileName(context: Context): String? {
} }
fun Uri.getFileSize(context: Context): Int { fun Uri.getFileSize(context: Context): Int {
val cursor = context.contentResolver.query(this, null, null, null, null, null) var fileSize: String? = null
if (scheme == ContentResolver.SCHEME_CONTENT) {
val fileSize = cursor?.use { try {
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) val fileInputStream = context.contentResolver.openInputStream(this)
if (cursor.moveToFirst()) { fileSize = fileInputStream.available().toString()
if (!cursor.isNull(sizeIndex)) { } catch (e: Exception) {
return@use cursor.getString(sizeIndex) e.printStackTrace()
} }
} else if (scheme == ContentResolver.SCHEME_FILE) {
val path = this.path
try {
val f = File(path)
fileSize = f.length().toString()
} catch (e: Exception) {
e.printStackTrace()
} }
return@use null
} }
return fileSize?.toIntOrNull() ?: -1 return fileSize?.toIntOrNull() ?: -1
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment