Guest User

Untitled

a guest
May 20th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. @Dao
  2. interface ConcertDao {
  3. // The Integer type parameter tells Room to use a PositionalDataSource
  4. // object, with position-based loading under the hood.
  5. @Query("SELECT * FROM user ORDER BY concert DESC")
  6. fun concertsByDate(): DataSource.Factory<Int, Concert>
  7. }
  8.  
  9. class MyViewModel(concertDao: ConcertDao) : ViewModel() {
  10. val concertList: LiveData<PagedList<Concert>> = LivePagedListBuilder(
  11. concertDao.concertsByDate(),
  12. /* page size */ 20
  13. ).build()
  14. }
  15.  
  16. class MyActivity : AppCompatActivity() {
  17. public override fun onCreate(savedState: Bundle?) {
  18. super.onCreate(savedState)
  19. val viewModel = ViewModelProviders.of(this)
  20. .get(MyViewModel::class.java!!)
  21. val recyclerView = findViewById(R.id.concert_list)
  22. val adapter = ConcertAdapter()
  23. viewModel.concertList.observe(this, { pagedList ->
  24. adapter.submitList(pagedList) })
  25. recyclerView.setAdapter(adapter)
  26. }
  27. }
  28.  
  29. class ConcertAdapter() :
  30. PagedListAdapter<Concert, ConcertViewHolder>(DIFF_CALLBACK) {
  31. fun onBindViewHolder(holder: ConcertViewHolder, position: Int) {
  32. val concert = getItem(position)
  33. if (concert != null) {
  34. holder.bindTo(concert)
  35. } else {
  36. // Null defines a placeholder item - PagedListAdapter automatically
  37. // invalidates this row when the actual object is loaded from the
  38. // database.
  39. holder.clear()
  40. }
  41. }
  42.  
  43. companion object {
  44. private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Concert>() {
  45. // Concert details may have changed if reloaded from the database,
  46. // but ID is fixed.
  47. override fun areItemsTheSame(oldConcert: Concert,
  48. newConcert: Concert): Boolean =
  49. oldConcert.id == newConcert.id
  50.  
  51. override fun areContentsTheSame(oldConcert: Concert,
  52. newConcert: Concert): Boolean =
  53. oldConcert == newConcert
  54. }
  55. }
  56. }
Add Comment
Please, Sign In to add comment