Last active
October 14, 2021 13:21
-
-
Save hamen/12e3ec9d94f799d189fd7c17f9a0acbd to your computer and use it in GitHub Desktop.
A couple of extensions on String and File to safely convert toUri()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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