Did you ever consider the users of your app could have no internet connection? Android Room will store data locally enabling a smooth offline experience. In this post we will show how to store data in a Room database and abstract this mechanism away using the Repository pattern.
We start off with the example app of a previous post on Android RecyclerView. The complete code for this post can be found here on github.
We will only cover some of the aspects of storing data in a local database. More information can be found on the android developers page here.
Room Database
We begin defining the objects we want to save in the database. We use a normal Kotlin data class with android room annotations. We annotate the class with @Entity and specify the name of the database table.
@Entity(tableName = "actions",
indices = [Index(value = ["code"], unique = true)])
data class DatabaseAction(
@PrimaryKey(autoGenerate = true)
var id: Long = 0L,
var title: String,
var code: String,
var description: String,
var type: String)
If you remember the domain object Action of the previous android post, you might notice that DatabaseAction is a copy except for the types and the id property. Not all types can be saved to the database so we need this representation.
Moreover we don’t want duplicate data in our database. Therefore we define an index on the action’s code. The database will now enforce that a DatabaseAction with an existing code can not be inserted.
Now we can define the methods to save and retrieve data from the actions table. Room has annotations that we can use to generate the implementations that we need. We collect them in the interface ActionDao annotated with @Dao.
@Dao
interface ActionDao {
@Query("SELECT * FROM actions ORDER BY id DESC")
fun fetchAllActions(): LiveData<List<DatabaseAction>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun insertAll(actionList: List<DatabaseAction>)
}
Note that with @Query we can run any SQLite query that we would like. For this SELECT query we can choose return type List<DatabaseAction> or LiveData<List<DatabaseAction>>. The latter updates if the database entities change.
With the insert annotation we can say what to do when the insertion of a DatabaseAction fails. For example on the unique index on code we defined. Here we ignore the insert and move on to the next.
The only thing left to do is to define the database. We set the @Database annotation and specify alle the entity classes it entails. It also extends RoomDatabase and holds a reference to the ActionDao we just created.
@Database(entities = [DatabaseAction::class], version = 1, exportSchema = false)
abstract class GardenPlannerDatabase: RoomDatabase() {
abstract val actionDao: ActionDao
...
}
Note that we did not talk about the database version. This is part of a whole different subject and will be out of scope for this post.
The Repository Pattern
We have everything in place to save and retrieve data from the database. But sometimes new is available from the ActionClient calling our (mocked backend). How can we provide a smooth experience and give our users the up to date data?
We use the repository pattern that appoints the database as the single source of truth and refreshes the database data with the data from the client. Below we see this pattern implemented.
class ActionRepository(private val database: GardenPlannerDatabase, private val actionClient: ActionClient) {
val actionList: LiveData<List<Action>> = Transformations.map(database.actionDao.fetchAllActions()) {
it.asDomainModel()
}
suspend fun refreshActions() {
withContext(Dispatchers.IO) {
val actionList = actionClient.fetchActions().await()
database.actionDao.insertAll(
actionList.asDatabaseEntities())
}
}
}
Note that the repository has to map the database entities to domain entities. Also note that we did not cover the withContext(Dispatchers.IO) part for it is part of android coroutines and will be the subject of a later post.
Run the app and how the first time the data is displayed with a delay of 5 seconds. This simulates it being fetched from a brittle internet connection. The second time goes much faster for the repository gets it from the database where the data is stored. Even without internet the user can scroll through its data.
Hopefully you can are now able to use Android Room to save data locally in your own apps. Happy rooming!
Wow, this article is fastidious, my younger sister is analyzing these kinds of things, thus I am going to let know her.|
If some one needs expert view regarding running a blog after that i suggest him/her to pay a visit this weblog, Keep up the nice work.|
Hi there, its good paragraph concerning media print, we all know media is a impressive source of data.|
Its not my first time to pay a visit this site, i am browsing this site dailly and obtain nice data from here all the time.|
If some one wishes expert view regarding blogging and site-building then i advise him/her to
pay a visit this blog, Keep up the good work.
excellent points altogether, you simply gained a emblem
new reader. What could you recommend in regards to
your post that you just made some days ago? Any positive?
Pretty! This has been an incredibly wonderful article.
Many thanks for supplying this info.
I got this web page from my buddy who shared with me about this website and
now this time I am browsing this web site and reading very informative posts
here.
I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your website to come back later on. Many thanks|
I am curious to find out what blog platform you have been utilizing?
I’m having some small security problems with my latest site
and I’d like to find something more risk-free.
Do you have any suggestions?
I enjoy reading a post that can make men and women think. Also, thank you for allowing me to comment!
Hello, i think that i saw you visited my web site thus i came to “return the favor”.I’m attempting to find things to improve my
site!I suppose its ok to use a few of your ideas!!
Thanks for one’s marvelous posting! I actually enjoyed reading it,
you can be a great author.I will ensure that I bookmark your blog and
will eventually come back later in life. I want to encourage you continue your
great writing, have a nice day!
This is my first time pay a visit at here and i am in fact impressed to read everthing at single place.
I feel this is among the such a lot important information for me.
And i’m satisfied reading your article. However should commentary
on few general things, The web site style is great,
the articles is truly excellent : D. Excellent process, cheers
Hmm it seems like your website ate my first comment
(it was extremely long) so I guess I’ll just sum it up what I wrote and say,
I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to
the whole thing. Do you have any suggestions for rookie blog
writers? I’d really appreciate it.
Hi, my advice would be to just start writing. Use you own site or an existing platform and write about what you learned this week/month for example. If you didn’t know it, I am sure there are others who are struggling with the same issue. Good luck!
I constantly spent my half an hour to read this blog’s posts every day along with a
mug of coffee.
Ahaa, its pleasant dialogue about this paragraph at this place at this weblog, I have read all that, so at this time me also commenting at this place.
Hello Dear, are you really visiting this site daily, if so then you will definitely get pleasant knowledge.|
Thanks for one’s marvelous posting! I definitely enjoyed
reading it, you happen to be a great author.I will be sure to bookmark your blog and will often come back later on. I want to encourage you to ultimately continue your great
work, have a nice holiday weekend!
May I just say what a comfort to uncover a person that genuinely understands what they are discussing on the web. You definitely understand how to bring an issue to light and make it important. More people should read this and understand this side of your story. It’s surprising you are not more popular since you certainly possess the gift.
Greetings! Very helpful advice in this particular post! It is the little changes that make the most significant changes. Thanks for sharing!
Nice post. I learn something totally new and challenging on blogs I stumbleupon every day. It will always be exciting to read through content from other authors and use something from other web sites.
Great blog you’ve got here.. It’s difficult to find good quality writing like yours these days. I truly appreciate individuals like you! Take care!!
Hi, I do think this is a great blog. I stumbledupon it 😉 I may revisit once again since i have saved as a favorite it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.
It’s hard to find well-informed people on this topic, however, you sound like you know what you’re talking about! Thanks
After going over a few of the articles on your site, I really appreciate your technique of blogging. I book marked it to my bookmark webpage list and will be checking back in the near future. Please visit my web site too and tell me how you feel.
Yes! Finally something about Mary.
hi!,I like your writing so much! percentage we keep
up a correspondence more about your post on AOL?
I require a specialist in this space to resolve my problem.
Maybe that is you! Having a look forward to look you.
Very reliable.
Good information. Lucky me I ran across your website by accident (stumbleupon). I’ve bookmarked it for later!
I could not refrain from commenting. Exceptionally well written!
Howdy! This article could not be written any better! Going through this post reminds me of my previous roommate! He always kept preaching about this. I most certainly will forward this information to him. Fairly certain he’ll have a good read. I appreciate you for sharing!
Greetings! Very useful advice in this particular article! It’s the little changes that will make the most significant changes. Thanks for sharing!
I really like it whenever people come together and share thoughts. Great blog, keep it up!
Hi, I do think this is an excellent website. I stumbledupon it 😉 I will revisit yet again since I bookmarked it. Money and freedom is the greatest way to change, may you be rich and continue to guide others.
Excellent blog you have here.. It’s hard to find quality writing like yours nowadays. I seriously appreciate individuals like you! Take care!!
After looking at a handful of the articles on your website, I really like your way of writing a blog. I book-marked it to my bookmark website list and will be checking back soon. Please visit my website too and let me know how you feel.
Spot on with this write-up, I seriously feel this web site needs a great deal more attention. I’ll probably be back again to read more, thanks for the information!
Great piece of content.
This website was… how do you say it? Relevant!! Finally I have found something that helped me. Thanks!
This is a topic which is close to my heart… Take care! Exactly where are your contact details though?
After I initially commented I appear to have clicked the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I get four emails with the exact same comment. There has to be a way you can remove me from that service? Cheers!
Hi, you can manage your own subscriptions here https://subscribe.wordpress.com/. Cheers!
What a great read – I’ll be sharing with my colleagues. This is appreciated!
I was able to find good information from your blog posts.
Great article! We will be linking to this great article on our website. Keep up the good writing.
I could not refrain from commenting. Exceptionally well written!
Your style is unique in comparison to other folks I have read stuff from. Thanks for posting when you’ve got the opportunity, Guess I will just book mark this site.
There is definately a great deal to find out about this issue. I really like all the points you’ve made.
Good write-up. I definitely love this website. Keep writing!
I simply want to mention I am just very new to weblog and certainly enjoyed you’re blog site. Probably I’m likely to bookmark your site . You amazingly come with remarkable writings. Bless you for sharing your web site.
Appreciation to my father who informed me about this blog,
this webpage is truly awesome.