Home > database >  Using room sqlite db for storing key value pairs like sharedpreferences
Using room sqlite db for storing key value pairs like sharedpreferences

Time:12-11

For some resons, I want to use sqlite as a replacement for sqlite I can use room db, create a table called preferences with a structure like this

| key | value |

| key1 | value1 |

| key2 | value2 |

Problem with this approach is value column can only be text but i want to store text/numbers

| key | value | type |

| key1 | value1 | string |

| key2 | value2 | int |

And based on type I can manualy use Integer.parse(stringValue) ..

But this looks like i'm reinventing a wheel

Is there any other approach I'm not able to grasp?

CodePudding user response:

If your datatype is not defined, instead of storing the datatype yourself, and figuring out which parsing function you need to perform, you could instead use JSON to store your data.

In your example, the value becomes a JSON encoded string. So, you can store any data type and parsing it is a single step, and you don't have to care about the datatype.

For example,

|Key                       |Value        |
|aStringVariable           |"Hello"      |
|anIntVariable             |1            |
|aBooleanVariable          |true         |

You just need to use a function to parse the JSON data when you retrieve it from the database and a function to encode data into JSON when you store it.

You haven't mentioned which language you are using, assuming Java, you can use GJson - https://www.javatpoint.com/how-to-convert-string-to-json-object-in-java.

Since you don't know the structure of your data, you can use a map when converting JSON into an object. It seems like all popular Java libraries do support this.

Here is a link that provides more details into how to parse and unparse JSON data into maps using gson and jackson (and a few others) - Convert a JSON String to a HashMap

  • Related