Skip to content

Instantly share code, notes, and snippets.

@hamen
Last active October 14, 2021 13:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamen/12e3ec9d94f799d189fd7c17f9a0acbd to your computer and use it in GitHub Desktop.
Save hamen/12e3ec9d94f799d189fd7c17f9a0acbd to your computer and use it in GitHub Desktop.
A couple of extensions on String and File to safely convert toUri()
import android.net.Uri
import java.io.File
/**
* Tries to convert a [String] to a [Uri].
* Differently from the "I'm 5 years old" implementation that comes with Android
* that throws a temper tantrum, i.e. exception, if the conversion fails,
* this implementation returns a [null], like an adult would do.
*/
@Suppress("SwallowedException", "TooGenericExceptionCaught")
fun String.toUriOrNull(): Uri? = try {
Uri.parse(this)
} catch (ignored: Exception) {
null
}
/**
* Tries to convert a [File] to a [Uri].
* Differently from the "I'm 5 years old" implementation that comes with Android
* that throws a temper tantrum, i.e. exception, if the conversion fails,
* this implementation returns a [null], like an adult would do.
*/
@Suppress("SwallowedException", "TooGenericExceptionCaught")
fun File.toUriOrNull(): Uri? = try {
Uri.fromFile(this)
} catch (ignored: Exception) {
null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment