faeze saghafi
faeze saghafi

Reputation: 658

android - How to get simple list from db using Room?

I am using Component libraries in my android app. in some case it is needed to use Livedata and observe its data but sometimes I just want to get some ordinary list not Livedata , How can I do that? query DB in simple way

p.s : I use getValue() but it returns null

Upvotes: 0

Views: 4602

Answers (2)

Jeel Vankhede
Jeel Vankhede

Reputation: 12118

Use query like this in DAO:

@Query("SELECT * FROM TABLE_NAME")
fun getListOfData(): List<Data>?

this will provide you list of data from your table, just like the select query passed in @Query parameter.


Edit:

When calling from main thread, you can use handler to do your job in background like below:

//Method from where you want your data from Db.
fun getMyList() {
    Thread {
        (your db object).(your dao).getListOfData()
    }.start()
}

or you can allow your db to execute on main thread when building your room db like below (Though i wouldn't recommend this) :

Room.databaseBuilder(
            ...
        )
                .allowMainThreadQueries()
                .build()

Upvotes: 2

P Vartak
P Vartak

Reputation: 460

You can simply write query in your Dao which has return type as List and call from your ViewModel where you need those data.

Example :

//YourDao

 @Query("SELECT * FROM YourTable")
List<YourModel> getAllYourTableData();

//YourRepo

public static List<YourModel> getAllData(){
return getYourModelDao.getAllYourTableData();
}

//Your ViewModel

public void someFunctionWhereYouNeedNormalData(){
//assign to list
YourRepo.getAllData();
}

Assuming you have knowledge about repo pattern in android arch components.

Upvotes: 0

Related Questions