How to model data when using Room - android

I am reading up on Room and the way it handles relationships between entities is both understandable, but confusing. I cannot wrap my head around what a "proper" data model should be to make Room happy. The problem is that all the examples I have found show how to handle a simple relationship, but don't address nesting, or entities that contain references to multiple other entities.
Going back to the beginning, my question is how should I model my data to make using Room as easy as possible?
Is it possible to have the data model framework-agnostic? That's something that feels correct to me. A framework should not dictate the way entities are modeled. I want to be able to traverse the data model as I would if there was no database at all.
Assuming I have a deep-ish hierarchy, for example: a Game has multiple Players and multiple Rounds. A Round has multiple Turns. A Turn can have multiple Steps. How do I model this according to Room? Reading about #Relation, it would suggest there should be "wrapper" POJOs. But would that mean that here I would have to create classes TurnWithSteps, RoundWithTurnWithSteps, and GameWithRoundWithTurnWithSteps?
This also seems to imply that whenever working with the entities in code, I have to decide which "view" of that entity to use. So I cannot simply work with Game and use it as if it was a true, nicely modeled class?

Related

Mapping model classes with Kotlin

I'm looking a way to improve the mapping mechanisms between the model classes from the different layers in my App.
I've model classes, the ones that I use in my App, in the business logic layer such as a Presenter. For example a User class.
I've server-side entities, these are the ones that I use to deserialize the responses from the server-side endpoints, through Retrofit or any other technology. These ones usually contain the Gson annotations for the fields. For example a ApiUserResponse class.
And I've DTO entities, these are the ones that represent a DB table in my App. I'm using Realm right now, but I've worked with ORMlite and Room. These types of classes also contain DB related annotations. For example a UserDTO class.
My cache repositories (the ones that fetch data from the DB) and my network repositories (the ones that fetch data from the server-side) both expose RxJava methods, returning the responses wrapped in Observable classes.
What I'm doing right now to parse the DTO entities and the server-side entities is add an extended function to the Observable class which receives a functions as argument. And that's the mechanism that I'm using to parse the DTOs and server-side entities into model classes. For example:
myLoginRepository.getUser("someId")
.mapTo(::myMappingFunction)
...
fun myMappingFunction(userResponse: ApiUserResponse): User {
return User(userResponse.id, userResponse.name, userResponse.lastname)
}
Internally the only thing that the mapTo extended function does is using a flatMap to flat the Observable stream and using a map to parse the collection.
I think that this is a pretty good way to implement the mapping between model-related classes, but I'm looking a way to improve it or do something completely different but that require less coding. Obviously this example is pretty straight forward, but currently I'm having a Mappings.kt file which is growing like crazy with each new mapping function.
Any suggestion?
Maybe http://modelmapper.org/ is something for you. This way you can spare your own mapping functions and you can even specify some sophisticated mapping functions. However it may cost you something in regards to performance (looks like reflection access all the way?).
Note: I didn't use the library myself yet, but it looks promising enough to recommend it. In the last project I helped out, they built their own modelmapper which probably wasn't such a good idea (lots of corner cases forgotten, which then led to strange behaviour later on or manually mapped the wrong fields; however your variant can suffer from that too).
Just found another article regarding mapping frameworks and their performance:
http://www.baeldung.com/java-performance-mapping-frameworks doesn't look that good for ModelMapper
You may also just want to generate your mapping functions. Similar to what you have now. Or just use a live template for it?
Manually writing your mappings may sooner or later introduce mistakes you are not identifying that easily anymore, except you test them all accordingly. Which you do, right? ;-)
You can convert your DTO object to entity or vice versa with converter.
Converter
ConversionService
You can implement Converter interface,It is a functional interface and you must implement convert method, then convert your DTO to entity, Where you want to convert them, just you should inject ConversionService and use convert method.
You should only have one class that representes both the entities and the model class from the network
If you want to use Room database and Retrofit for Api calls you should use like this
#Entity("tableName = something")
data class Something{
#SerializedName("name")
val name : String,
#SerializedName("number")
val number : Int}

Android - SQLite Database with Object Models

I am creating an Application in Android that uses a SQLite database. So far i have 3 table, one of which is used to link the first two tables together with foreign keys.
I have been reading a lot online about CursorLoaders, Content Providers, AsyncTask, URI's.... etc. A content provider seems like over-kill for my application, I do not intend to share this SQLite data with other applications.
My question: Is it a good idea in Android to create an object model of each row of Data from the database? My application wouldn't realistically have more than 500 objects from these databases, but is this good design/approach?
More Details: If I were to go down the Object route, I would use these objects and map them to Listviews mostly. Some of these objects may contain arraylists of other objects, Say for instance mapping these kinds of objects to expandable listviews. I tried this approach and it worked really well, I am just unsure of making all of these objects is wasting resources, slowing things down, or will it become a problem later if I decide to expand the application? What if i had 5000 Objects? Just unsure if it's a valid programming approach.

SQLite or Serialization

I'm writing an application which needs to store data. A single pack of data is about 4 classes with many dependencies between them. For example, class A has a list of objects B and B has a list of objects C and few more dependencies...
And I wonder what would be better. Keep them in SQLite db or serialize each pack separately and store them in serialized files?
For me the only right solution would be to save the data inside a database especially if there are any dependencies. For beginners it might be hard at the beginning to get into database creation. but after you have created a database in the right form you just have to insert the data and you won't have any problems in the future if you want to change something or expand your app. With simple serialisation the logic has to be solved inside the app and might cause more problems especially if you have any dependencies.
If you need a good tutorial for saving data you should look at this tutorial
http://thenewboston.org/watch.php?cat=6&number=111
For other different solutions for saving data there are also some tutorials on the website, Nr. 108 - 110 of Android programming
IT depends on the usage of the data. You may do well choosing JSON/GSON serialization and avoid the overhead of doing ORM over SQLite. (Overhead meaning additional coding to marshall to/from the db) However, if your data is subject to growth or something that would be better managed by a db (a lot of non-sequential or random access across a larger data set) then go for SQLite and ORM. In the end it comes down to what type of data you are trying to manage. Again if your data set is something that could grow and involves a lot of random access it may be worth using SQLite.

How to Properly Structure my Android App, Classes, Views, Databases, Made Simple?

I'm having a hell of time grasping the best way to "package" my Android app into logical components, my objective is to make an app that is easy to update and add new features to.
I believe a "modular" approach would work best, one where my data is represented as Data Classes, my DB has it's own DB Helper Class which handles all DB interaction and finally View "Controller" Activity Classes which interface the DB Helper, Data Classes and Views all together.
This being said, I need some high-level rules in order to structure my programming, I find if I don't have rules, I end up with sloppy code and massive rewrites as the code gets too complex.
All things considered, are these rules a good foundation for a SQL backed App?
My theoretical Android rules:
The DB Helper Class should contain all DB logic. This means, the DB Helper will contain the code to open and close the DB, as well as the code for inserting, updating and deleting all records. The DB Helper will return data not as cursors, but as Data Class objects that I create, each Data Class will have a constructor which takes the cursor and uses it to populate the values of the Class.
Data Classes will allow DB records to be represented as objects and not just cursors. As the DB Helper will only be returning objects I will have to create adapters for items such as ListView's to render my object's data as opposed to the cursor (I'm a bit fishy on this point, not sure if this is a good idea or not). All business logic, so all calculations to be done on the data contained in the Data Class, will be done in the Data Class itself. I envision my Data Classes having typical getters and setters as well as "calculate" methods, these calculate methods will take vars from the Data Class and do some meaningful business logic on them, returning the result (is this a good idea?).
View Controller Activity Classes will literally tie the DB Helper's methods to the Data Classes and update the Views with the resulting information. This Activity Class will be quite normal, it will initialize the layout and widgets, it will use the life-cycle methods to perform various queries on the DB through the DB Helper at the appropriate times, and it will have simple update methods which update widgets using the Data Class object they're fed.
I am finding I have no troubles with Android except for struggling with issues of design such as these. I am tired of my applications becoming too complex, and I need a simple system to ensure things stay manageable and extensible.
If you struggled like me, please, please, please, push me in the right direction for structuring an App. It's all that's holding me back from making what I hope are amazing apps for everyone's enjoyment.
The biggest thing you need to consider when designing your app is: who is going to maintain it? If you are going to be the only one who is doing maintanence on your app, then do whatever works best for you. However, if others are going to be maintaining this app, then yes, you will want to keep similar things together. It sounds like you have a pretty good plan. Make sure you use comments and if you like, you can include a "readme.txt" that will allow others to see what is going on and for you to explain your design logic. To keep things from becoming too complex, you can use packages to store similar classes.
Ultimately there is no single right answer to your question.

Store JSON in an sqlite field?

I'm writing an application that communicates with a web API, which responds with JSON. Currently, I'm translating the JSON objects to Java objects using gson (which is awesome, by the way).
Now, I want to store some of these objects in an SQLite database. However, they have lots of properties that would never be used in queries (i.e. I won't be ORDERing, WHEREing, or anything like that with those properties), so I feel it's unnecessary to create columns for all of them. What I'm thinking of doing is:
Only have columns for the essential data that will be used when querying the database
Have one TEXT or BLOB column (which one do you recommend?) that stores the actual JSON, so I can recreate my Java object from it and access all the data.
This would both make my life easier and streamline my code (I would not have to write very different code when dealing with data from the API vs. data from the database).
However, although I see no downsides, it feels a bit fishy.
What kind of trouble do you think I would run into if I use this technique?
The main thing I wouldn't like about it is relying on the structure of the stored/retrieved JSON to be valid, since it's completely out of the hands of the database. Not that you can't take precautions against possible issues, but if the JSON is somehow truncated or otherwise compromised in a way that trips up the parser, you're then missing the entire object instead of just one invalid or truncated property. If that's an acceptable risk, then it's probably a reasonable technique.

Categories

Resources