What is the best method of converting android.net.Uri
that it can be used with RoomDatabase
?
A Uniform Resource Identifier (URI) is a compact string of characters for identifying an abstract or physical resource.
It is an immutable one-to-one mapping to a resource or data. The method Uri. parse creates a new Uri object from a properly formated String .
Type converters let you convert one type to another type. Each type that you declare can optionally have a TypeConverter associated with it using the TypeConverterAttribute. If you do not specify one the class will inherit a TypeConverter from its base class.
The best way to store and retrieve Uri
with Room is to persist it in the form of String
. Moreover we already have the APIs to convert Uri
to String
and vice versa.
There are 2 ways:
Uri
to String
and then storing it and same for fetching.TypeConverter
.It's completely your choice and the app requirements to choose the way. That said, here is the TypeConverter
for Uri
<-> String
:
class UriConverters {
@TypeConverter
fun fromString(value: String?): Uri? {
return if (value == null) null else Uri.parse(value)
}
@TypeConverter
fun toString(uri: Uri?): String? {
return uri?.toString()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With