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任务被贬低,我怎么能改变我的代码到最新请帮助我
你可以使用协程,因为你已经在使用kotlin
这里有一个可以帮助你的代码库
0
https://developer.android.com/codelabs/android-room-with-a-view-kotlincodelab显示了类似的用法,所以我认为我没有必要再发布更多的代码片段
附加一个简短的代码片段来显示协程是如何工作的
在onViewCreated
viewLifecycleOwner.lifecycleScope.launch {
db.bookDao().getAllBooks()
}
在BookDao
在gettallbooks()方法之前使用suspend
suspend from getAllBooks(): List<Books>
这就是你所做的。