简体   繁体   中英

How to properly support different units in Room Database?

I am using Room Database in my Android App. One of the columns represents volume of drink in milliliters [ml]. I wonder what is the proper way of giving user option to choose/change units to [cl] or other. Should I make a settings option to choose unit, and then convert all values in my database? Should I store for example [ml] and then convert values depending on units selected by user? What is the most efficient way? What will be less resources consuming? Are You guys having some good open source examples/tutorials/code snippets?

It really depends on the volume and complexity of your conversions. If you only have a single value (ML) and need to convert it to another value (CL, OZ...) then you can just set a base unit to the DB and convert the value in real time just before displaying them to the user.

If you feel this will get out of hand since you'll have many value types and you'll have a problem keeping track on all of them you can do the conversion in the DB that will cause some overhead on the select queries. for example, you have this table:

ID  unit  val
--- ---   ---
1   ML    960
2   ML    4112
3   KG    70
4   KG    35
5   C     37

You'll always keep base units in the DB the same meaning you will not mix them with F, OZ and LBS. You can convert the units in your select query:

SELECT id, unit, val, 
    case when unit = 'ML'  then val * 0.033 
         when unit = 'KG'  then val / 2.205 
         when unit = 'C'   then val * 9/5 + 32
         end as result
FROM tbl

In both cases, since this is an Android app the work will be done via SQLite or the app itself. Personally, I would not mix units on the same table because it would add a layer of complexity to later sort, compare and retrieve them. Hope that helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM