Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best TypeConverter for Uri?

What is the best method of converting android.net.Uri that it can be used with RoomDatabase?

like image 574
YBrush Avatar asked Mar 25 '18 16:03

YBrush


People also ask

What is the use of URI in Android Studio?

A Uniform Resource Identifier (URI) is a compact string of characters for identifying an abstract or physical resource.

What is URI parse in android?

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 .

What is a TypeConverter?

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.


1 Answers

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:

  1. You'll handle the conversion of Uri to String and then storing it and same for fetching.
  2. Let Room do that for you using a 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()
    }
}
like image 148
Akshay Chordiya Avatar answered Oct 05 '22 00:10

Akshay Chordiya