PandaPlaysAll
PandaPlaysAll

Reputation: 1367

Android ROOM - How to Insert a Object inside an Object (i.e. Flash Card Deck has a List of Questions)

As per the title, I have been confused on how I would implement the following: A FlashCard deck has a title, due date (both have been implemented). However, it also contains a List of Cards. A Card is made up of a question and answer.

Like this, Deck(title, duedate, flashcards). Cards(question, answer)

I have been thinking about using a dedicated typeconverter for this. However, it can also get messy.

For example, I was thinking of having a type converter which collects all the existing questions and answers into a concatonated csv string. Then it will deconvert this when transitioning back into the object.

This method seems quite complicated. Therefore, I was wondering what is the best practice per se, for this sort of thing.

Thanks...

Upvotes: 0

Views: 190

Answers (1)

Sayok Majumder
Sayok Majumder

Reputation: 1091

I do think your problem is a database schema problem. So basically there are 2 solutions depending on how you want to use the cards.

1. If the card does not repeat in any deck or if each and every card is unique:

Then you can use this schema:-enter image description here

For finding all cards for a particular deck say suppose "Deck 1" whose id is 1. You can use the SQL query "SELECT * FROM Cards WHERE Deck_id=1;"

Pros:

  • You will have to maintain only two tables.
  • Probably easy to write SQL Queries.

Cons

  • You cannot reuse any cards. All cards will be unique.
  • May require more storage space.

2. If the card repeats, or if you want to reuse a card:

Then you can use this schema:-enter image description here

For finding all cards for a particular deck say suppose "Deck 1" whose id is 1. You can use the SQL query "SELECT * FROM Cards WHERE id IN(SELECT Cards_id FROM Deck_has_Cards WHERE Deck_id=1);"

Pros:

  • Saves a lots of storage space(if cards are not unique).

Cons

  • Queries become very hard to write

I will recommend you to check for better SQL queries than those I have written.

If you are using Room Database use @Query(<SQL>)...(I am not expanding on this many tutorials are available).

I will not recommend the way you are trying to store the cards as it will be not working with the A.C.I.D. properties of the database.

Upvotes: 1

Related Questions