【问题标题】:since Aysnc task is depriciated what alternative I can use and how to use因为 Asynctask 已被弃用,我可以使用什么替代方案以及如何使用
【发布时间】:2021-10-12 07:37:34
【问题描述】:
class FavouritesFragment : Fragment() {
lateinit var recyclerFavourite:RecyclerView
lateinit var progressLayout:RelativeLayout
lateinit var progressBar:ProgressBar
lateinit var layoutManager:RecyclerView.LayoutManager
lateinit var recyclerAdapter: FavouriteRecyclerAdapter
var dbBookList=listOf<BookEntity>()


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val view=inflater.inflate(R.layout.fragment_favourites, container, false)
    recyclerFavourite=view.findViewById(R.id.recyclerFavourite)
    progressLayout=view.findViewById(R.id.progressLayout)
    progressBar=view.findViewById(R.id.progressBar)
    layoutManager=GridLayoutManager(activity as Context,2)
    dbBookList=RetrieveFavourites(activity as Context).execute().get()
    if(activity!=null)
    {
        progressLayout.visibility=View.GONE
        recyclerAdapter= FavouriteRecyclerAdapter(activity as Context,dbBookList)
        recyclerFavourite.adapter=recyclerAdapter
        recyclerFavourite.layoutManager=layoutManager
    }
    return view
}
class RetrieveFavourites(val context: Context):AsyncTask<Void,Void,List<BookEntity>>()
{
    override fun doInBackground(vararg p0: Void?): List<BookEntity> {
        val db= Room.databaseBuilder(context,BookDatabase::class.java,"books-db").build()
        return db.bookDao().getAllBooks()
    }

}

}

上面的代码用于在单击“添加到收藏夹”按钮时将一本书添加到收藏夹数据库,现在由于 aysnc 任务已被贬低,如何将我的代码更改为最新,请帮助我

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    你可以使用协程,因为你已经在使用 kotlin

    这里有一个可以帮助你的代码实验室

    https://developer.android.com/codelabs/android-room-with-a-view-kotlin#0

    codelab 显示了类似的用例,所以我认为我不必再发布 sn-ps

    附上一段短代码 sn-p 来展示协程是如何工作的

    在 onViewCreated 中

    viewLifecycleOwner.lifecycleScope.launch {
      db.bookDao().getAllBooks() 
    }
    

    在书道

    在 getAllBooks() 方法之前使用暂停

    suspend from getAllBooks(): List<Books>
    

    这就是你所做的一切。

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 2015-08-10
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      相关资源
      最近更新 更多