0

i have an image Uri File and i need to check if that file is larger than 1mb. here is a piece of what i tried:

val uriFile  = selectedPhotoUri!!.toFile()
uriFileLength = (uriFile.length().div(1024))

application crashed

also I've tried that:

val uriFile :File = File(selectedPhotoUri.toString())
uriFileLength = (uriFile1.length().div(1024))

uriFileLength always returns as 0 also i am using Kotlin, I searched on this forum but only found java codes. thanks in advance.

Giorgos Neokleous
  • 1,709
  • 1
  • 14
  • 25
nick isra
  • 99
  • 1
  • 9
  • 567.div(1024) is 0 ;-). You have to query() the getContentResolver() with the uri you obtained. – blackapps Oct 07 '19 at 09:53
  • Possible duplicate of [Get the size of an Android file resource?](https://stackoverflow.com/questions/6049926/get-the-size-of-an-android-file-resource) – shb Oct 07 '19 at 10:12

1 Answers1

0

You should cast either your .length() . or 1024 into a float or a double, otherwise the operation will return an integer which in case the file size is less than 1024 will return 0.

For example:

Integers

256 / 1024 = 0

Doubles or Float

256 / 1024 = 0.25

So you can have something like:

fun File.getFileSizeFloat(): Float {
    return this.length().toFloat().div(1024)
}

fun File.getFileSizeDouble(): Double {
    return this.length().toDouble().div(1024)
}

// call to get file size
uriFile.getFileSizeDouble()

// or
uriFile.getFileSizeFloat()
Giorgos Neokleous
  • 1,709
  • 1
  • 14
  • 25
  • i tried your method but still it's returning 0.0 now, i didnt downvote btw. – nick isra Oct 07 '19 at 12:12
  • If it still returning 0, then your URI is not valid. If you try `uriFile.exists()`, does it return `true`? – Giorgos Neokleous Oct 07 '19 at 12:14
  • tried uriFile.exists() returned false, i think my problem is that my uri file can not be transformed into a file by using File() or .toFile() , also the suggested answer is in java and can't be used in kotlin? correct me if i am wrong , i started learning kotlin not long ago. thank you – nick isra Oct 07 '19 at 13:30
  • @nickisra the answer is in Kotlin, and they are extension functions which are only available in Kotlin. How do you get your URI? I will suggest to use the `path` to create the File object, from there my answer should be sufficient. See how to get the path from URI: https://stackoverflow.com/a/7726604/3330058 – Giorgos Neokleous Oct 07 '19 at 13:48
  • thanks for your help, i solved the problem 1 min ago by using documentFile dependency – nick isra Oct 07 '19 at 13:54
  • @nickisra nice to hear that you solved it. If my answer helped to solve the initial question of the file size, please mark it as the correct one. – Giorgos Neokleous Oct 07 '19 at 13:57