如何从线程返回值?

时间:2019-05-21 18:33:08

标签: android database multithreading kotlin return-value

我想将arrayList传递给适配器构造函数。返回Arraylist 通过查询。查询必须在线程中。我该怎么办?

CostDao.kt

@Dao
interface CostDAO {

    @Query("select * from Cost")
    fun getAll() : List<Cost>

MainActivity.kt



class ComparatorActivity : AppCompatActivity(), OpenDatabase.OpenDatabaseListener {
    private var db: AppDatabase? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        val open = OpenDatabase(this)
        open.setOpenDatabaseListener(this)
        open.load()
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        Threads()


//i need to pass the arraylist
        val adapter = MyAdapter(this, )

        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
        recyclerView.adapter = adapter

}
    fun Threads() {
        Thread {
            val List = db!!.costDAO().getAll()
        }.start()
}


如何从线程返回列表?然后将其传递给适配器构造函数。

2 个答案:

答案 0 :(得分:0)

您可以将一个空列表传递给适配器构造函数,并在从数据库中检索数据时调用adapter.notifydatasetchanged(),但该列表必须是同一对象。

class ComparatorActivity : AppCompatActivity(), OpenDatabase.OpenDatabaseListener {
    private var db: AppDatabase? = null
    var list = listOf<Cost>()
    private lateinit var adapter: MyAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)

        val open = OpenDatabase(this)
        open.setOpenDatabaseListener(this)
        open.load()
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)

        adapter = MyAdapter(this,list)
        Threads()

        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
        recyclerView.adapter = adapter
    }
    fun Threads() {
        Thread {
            list = db!!.costDAO().getAll()
            adapter.notifyDataSetChanged()
        }.start()
}

答案 1 :(得分:0)

在数据准备好后创建Adapter的新实例并将其设置为您的recyclerView

Thread {
    val itemsList...// from db
    runOnUiThread {
        recyclerView.adapter = MyAdapter(this, itemsList)
    }
}.start()

您也可以在您的setItems中创建一个adapter方法并以这种方式分配它:

class MyAdapter... {

    private val items = mutableListOf<Cost>()

    fun setItems(items: List<Cost>) {
        this.items.clear()
        this.items.addAll(items)
        notifyDataSetChanged()
    }
}

Thread {
    val itemsList...// from db
    runOnUiThread {
        (recyclerView.adapter as MyAdapter).setItems(itemsList)
    }
}.start()

我还建议使用AsyncTask代替常规线程