简体   繁体   English

android-如何使用Room从数据库获取简单列表?

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

I am using Component libraries in my android app. 我在我的android应用程序中使用组件库。 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? 在某些情况下,需要使用Livedata并观察其数据,但是有时我只是想获取一些普通列表而不是Livedata,我该怎么做? query DB in simple way 以简单的方式查询数据库

ps : I use getValue() but it returns null ps:我使用getValue()但它返回null

Use query like this in DAO : 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. 这将为您提供表中的数据列表,就像@Query参数中传递的选择查询一样。


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()

You can simply write query in your Dao which has return type as List and call from your ViewModel where you need those data. 您可以简单地在Dao中编写查询,查询的返回类型为List,并在需要这些数据的ViewModel中调用。

Example : 范例:

//YourDao // YourDao

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

//YourRepo // YourRepo

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

//Your ViewModel //您的ViewModel

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

Assuming you have knowledge about repo pattern in android arch components. 假设您了解android arch组件中的回购模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM