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()
}
}
}
The above code is used to add a book to the favourites database when button add to favourites is clicked ,now since aysnc task is depriciated how can I change my code to latest please help me
you can use coroutines for same since you are already using kotlin
here's a codelab which can help you
https://developer.android.com/codelabs/android-room-with-a-view-kotlin#0
codelab shows similar usecase you have so i don't think i have to post anymore snippets
attaching a short code snippet to show how coroutines work
in onViewCreated
viewLifecycleOwner.lifecycleScope.launch {
db.bookDao().getAllBooks()
}
in BookDao
use suspend before your getAllBooks() method
suspend from getAllBooks(): List<Books>
this is all you do.