Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is recommended not to use allowMainThreadQueries() for Android room?

I'm creating a small app that just save some counters in a database. If it doesn't exists, insert one. And If it does, increase an update.

The app doesn't have any UI. It's a plugin that save and read data (small amount of tables, small amount of records).

Can I use allowMainThreadQueries() in this case? Everytime I read some tutorial about this framework always says that I shouldn't use it in production.

like image 846
Mariano L Avatar asked Oct 26 '18 00:10

Mariano L


People also ask

Is Android room an ORM?

Is Android Room an ORM? Room isn't an ORM; instead, it is a whole library that allows us to create and manipulate SQLite databases more easily. By using annotations, we can define our databases, tables, and operations.

What is fallbackToDestructiveMigration in room?

fallbackToDestructiveMigration() Allows Room to destructively recreate database tables if Migration s that would migrate old database schemas to the latest schema version are not found.

What is Android room used for?

Room is a persistence library, part of the Android Architecture Components. It makes it easier to work with SQLiteDatabase objects in your app, decreasing the amount of boilerplate code and verifying SQL queries at compile time.


2 Answers

From Developers documentation https://developer.android.com/training/data-storage/room/accessing-data

Note: Room doesn't support database access on the main thread unless you've called allowMainThreadQueries() on the builder because it might lock the UI for a long period of time. Asynchronous queries—queries that return instances of LiveData or Flowable—are exempt from this rule because they asynchronously run the query on a background thread when needed.

like image 37
eurosecom Avatar answered Sep 22 '22 09:09

eurosecom


The main reason it is not recommended to run Database queries on UI thread is because databases usually carry a lot of data and querying will take a lot time and hence block your UI.

In your case as you only have one counter, you can do it on main thread with allowMainThreadQueries. And all of those "Not recommended" will not have effect on your performance, because it doesn't involve a lot of data. But then, having single counter in your database will contradict the point of Database (in your case Room). Such counters are usually stored in SharedPreference

like image 184
musooff Avatar answered Sep 20 '22 09:09

musooff